fbpx

Get HTML Element Width Using Raw JavaScript

Sometimes you don’t want to add the jQuery library to your project and just want to use raw JavaScript. In this case, you will use the following commands to get the HTML element width using raw JavaScript.

We’ll show you how to get the width of an element with a certain id, how to get the width of an element with a certain class, how to get the width of the window, and how to get the width of the HTML body.

Get Width of an HTML Element by ID

The following JavaScript code gets the element width with and without a border of an element with the id value of container.

// get width with border
document.getElementById("container").offsetWidth
// get width without border
document.getElementById("container").clientWidth

Get Width of an HTML Element by Class

The following JavaScript code gets the element width with and without a border of an element with the class value of container.

// get width with border
document.getElementsByClassName("container")[0].offsetWidth;
// get width without border
document.getElementsByClassName("container")[0].clientWidth;

Get Width of the HTML Body

The following JavaScript code gets the width of the HTML body.

document.body.clientWidth

Get Width of the Window

The following JavaScript code gets the width of the window.

window.innerWidth

Leave a Reply

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