Categories
JavaScript Answers

How to Get the Width of an Element in Pixels that has the Style CSS Property Set with % with JavaScript?

Spread the love

To get the width of an element in pixels that has the style CSS property set ith % with JavaScript, we can use the clientWidth property of the element.

For instance, if we have the following HTML:

<div style="width: 100%; height: 10px;"></div>

with the width set to 100% and we want to get the width in pixels.

Then we can get the width of the div in pixels by writing:

const {  
  clientWidth  
} = document.querySelector('div')  
console.log(clientWidth)

We select the div with document.querySelector .

And then we destructure the clientWidth property from the selected element object.

clientWidth is the width of the div in pixels.

Conclusion

To get the width of an element in pixels that has the style CSS property set ith % with JavaScript, we can use the clientWidth property of the element.

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 *