Finding an element's size and position
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Finding an element's size and position
Sometimes, you need to know the width and height of your element. You may also need to know where the element is located in the document.
Getting this information is easy with getBoundingClientRect
.
const domRect = element.getBoundingClientRect();
domRect
is an object that contains 6 values:
top
– the distance from the top of the document to the top of the element
bottom
– the distance from the top of the document to the bottom of the element
left
– the distance from the left of the document to the left of the element
right
– the distance from the left of the document to the right of the element
width
– the width of the element
height
– the height of the element
There are two more values, x
and y
, but they mean the same thing as left
and top
.
Exercise
Go to any web page, open up your console and get use getBoundingClientRect
to get at the DomRect of at least one element. You should see eight values.