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:

  1. top – the distance from the top of the document to the top of the element
  2. bottom – the distance from the top of the document to the bottom of the element
  3. left – the distance from the left of the document to the left of the element
  4. right – the distance from the left of the document to the right of the element
  5. width – the width of the element
  6. height – the height of the element
getBoundingClientRect returns the distances from the viewport to the element in pixels
getBoundingClientRect returns the distances from the viewport to the element in pixels

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.