published: 18 Jun 2022
2 min read
Get height and width of an element using JavaScript
To get the height and width of an HTML element, you can use the offsetHeight
and offsetWidth
properties.
These properties return the viewable height and width of an element in pixels, including border, padding, and scrollbar, but not the margin.
Here is an example:
const pizza = document.querySelector('.pizza');
const height = pizza.offsetHeight;
const width = pizza.offsetWidth;
To skip the border and scrollbar, and get the width and height that just include padding, you can use the clientWidth
and clientHeight
properties:
const pizza = document.querySelector('.pizza');
const height = pizza.clientHeight;
const width = pizza.clientWidth;
Are we missing something? Help us improve this article. Reach out to us.
Get height and width of an element using JavaScript
To get the height and width of an HTML element, you can use the offsetHeight
and offsetWidth
properties.
These properties return the viewable height and width of an element in pixels, including border, padding, and scrollbar, but not the margin.
Here is an example:
const pizza = document.querySelector('.pizza');
const height = pizza.offsetHeight;
const width = pizza.offsetWidth;
To skip the border and scrollbar, and get the width and height that just include padding, you can use the clientWidth
and clientHeight
properties:
const pizza = document.querySelector('.pizza');
const height = pizza.clientHeight;
const width = pizza.clientWidth;
Are you looking for other code tips?
JS Nooby
Javascript connoisseur