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 HTML element width using raw JavaScript. We’ll show you how to get the width of an element with a certain id and with a certain class and how to get the width of the window and of the HTML body.

Get Width of an HTML Element by ID

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

Get Width of an HTML Element by Class

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

Get Width of the HTML Body

document.body.clientWidth

Get Width of the Window

window.innerWidth

Leave a Reply

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