Using offsetWidth
The DOM offsetWidth property is used to return the layout width of an element as an integer.
Example 1: The following program will illustrate the solution using offsetWidth
html
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < title >Check Width</ title > < style > body{ display: flex; justify-content: center; align-items: center; } #GFG { height: 30px; width: 300px; padding: 10px; margin: 15px; background-color: green; } #checkButton { padding: 5px 10px; cursor: pointer; } </ style > </ head > < body > < div id = "GFG" > < b >Division</ b > </ div > < button id = "checkButton" onclick = "checkWidth()" > Check Width </ button > < script > function checkWidth() { const elemWidth = document.getElementById("GFG").offsetWidth; alert("Width of the div: " + elemWidth + " pixels"); } </ script > </ body > </ html > |
Output:
How to find the width of a div using vanilla JavaScript?
To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels.
Below are the different approaches to finding the width of a div using vanilla JavaScript:
Table of Content
- Using offsetWidth
- Using clientWidth()
- Using getComputedStyle()
- Using getBoundingClientRect()