Categories
JavaScript Answers

How to Find the Width of an Element Using Vanilla JavaScript?

Spread the love

Sometimes, we want to find the width of an element with vanilla JavaScript.

In this article, we’ll look at how to find the width of an element with vanilla JavaScript.

HTMLElement.offsetWidth

One property we can use to find the width of an element is the offsetWidth property.

It’s a read-only property that returned the layout width of an element as an integer.

It’s measured in pixels of the element’s CSS width, including borders, padding, and vertical scrollbars if it’s rendered.

And it doesn’t include the width of any pseudo-elements.

If the element is hidden, then 0 is returned.

For instance, we can write the following HTML:

<p>  
  hello world  
</p>

Then we can get the offsetWidth by writing:

const p = document.querySelector('p');  
console.log(p.offsetWidth)

HTMLElement.clientWidth

Another property we can use to get the width of an element is the clientWidth property.

It’s zero for inline elements and elements with no CSS.

Otherwise, it’s the inner width of an element in pixels.

It includes padding but excludes borders, margins, and vertical scrollbars if present.

For instance, we can write the following HTML:

<p>  
  hello world  
</p>

Then we can get the offsetWidth by writing:

const p = document.querySelector('p');  
console.log(p.clientWidth)

to get the clientWidth property.

Using the getComputedStyle Function

The getComputedStyle global function returns an object containing the values of all CSS properties of an element after the active stylesheets and basic computations are applied to it.

We can access the individual CSS properties from the returned object.

The width property would have the computed width of an element after the stylesheets, changes in width with JavaScript, etc. are applied to it.

For instance, we can write:

const p = document.querySelector('p');  
console.log(getComputedStyle(p).width)

Then we get the width of the p element with the unit as a string.

Conclusion

There’re various properties and methods we can use to get the width of an element with vanilla JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *