JavaScript: 4 Ways to Get the Width & Height of an Element

Updated: March 16, 2023 By: Khue Post a comment

This succinct, practical article will walk you through a couple of different ways to get the width and height of an element using JavaScript.

Inspecting the Width & Height of an Element

Let’s say we have an element with an id of box. The first thing we have to do is to get a reference to this element:

const box = document.querySelector('#box');

offsetWidth & offsetHeight

The first way to find the size of the element is to use its offsetWidth and offsetHeight properties, which return the total amount of space an element occupies, including border, padding, and scrollbar:

const offsetWidth = box.offsetWidth;
const offsetHeight = box.offsetHeight;
console.log(`Offset: ${offsetWidth} x ${offsetHeight}`);

clientWidth & clientHeight

The second way is to use the clientWidth and clientHeight properties of the element, which return how much space the actual displayed content takes up, including padding but not including border, margins, or scrollbars:

const clientWidth = box.clientWidth;
const clientHeight = box.clientHeight;
console.log(`Client: ${clientWidth} x ${clientHeight}`);

getBoundingClientRect()

The third way is to call the getBoundingClientRect() method of the element, which returns a DOMRect object that contains information about its position and size after CSS transformation:

const rect = box.getBoundingClientRect();
const rectWidth = rect.width;
const rectHeight = rect.height;
console.log(`Rect: ${rectWidth} x ${rectHeight}`);

window.getComputedStyle()

You can use getComputedStyle() to get the width and height of an element when you want to inspect the element’s style after applying active stylesheets and resolving any basic computation those values may contain. For example, if you have an element with a width of 50% of the viewport, you can use getComputedStyle() to get its actual pixel value.

// Get the computed style of the box element
const style = window.getComputedStyle(box);

// Get the width and height properties from the style object
const width = style.getPropertyValue("width");
const height = style.getPropertyValue("height");

Note that you cannot use getComputedStyle() to get the width and height of an element when you want to inspect styles directly added to it from JavaScript manipulation or the global style attribute.

What if the Element’s Size Changes Dynamically?

ResizeObserver

You can listen to the size of an element and log the size when it changes by using the ResizeObserver API, which allows you to observe changes in the size of one or more elements. The ResizeObserver constructor takes a callback function that is invoked whenever an observed element’s size changes. The callback function receives an array of ResizeObserverEntry objects, each containing information about an observed element’s content rect and border box.

Here is an example code snippet that uses ResizeObserver to log the width and height of a div element:

// Get a reference to a div element
const div = document.querySelector('div');

// Create a new ResizeObserver instance
const resizeObserver = new ResizeObserver(entries => {
  // Loop over the entries
  for (let entry of entries) {
    // Get the element's content rect
    const {width, height} = entry.contentRect;
    // Log its width and height
    console.log(`Element's width: ${width}, height: ${height}`);
  }
});

// Start observing the div element
resizeObserver.observe(div);

If you want to use offsetWidth and offsetHeight instead of contentRect, you can access the target property of the ResizeObserverEntry object, which is a reference to the observed element. Then you can use its offsetWidth and offsetHeight properties to get its size:

// Get a reference to a div element
const div = document.querySelector('div');

// Create a new ResizeObserver instance
const resizeObserver = new ResizeObserver(entries => {
  // Loop over the entries
  for (let entry of entries) {
    // Get the observed element
    const element = entry.target;
    // Get its width and height using offsetWidth and offsetHeight
    const width = element.offsetWidth;
    const height = element.offsetHeight;
    // Log its width and height
    console.log(`Element's width: ${width}, height: ${height}`);
  }
});

// Start observing the div element
resizeObserver.observe(div);

window.addEventListener(“resize”)

In case you only need to update the size of an element on window resize, you can define a JavaScript function that gets the new width and height of the element and attach this function to the window resize event using addEventListener, like this:

// Define a function that gets the size of an element
const getSize = (element) => {
  // Get the width and height properties of the element
  var width = element.clientWidth;
  var height = element.clientHeight;

  // Log the width and height values to the console
  console.log("The width of the element is " + width + " pixels.");
  console.log("The height of the element is " + height + " pixels.");
}

// Get an element by its id
var myElement = document.getElementById("my-element");

// Call the getSize function once to get the initial size
getSize(myElement);

// Add an event listener for window resize
window.addEventListener("resize", function() {
  // Call the getSize function again to get the new size
  getSize(myElement);
});

A Complete Example

Preview

We’re going to make a sample webpage that displays an orange box. The width of the box is 50% of the viewport. The height is based on its content (some dummy text). The box also has some inner padding.

We’re going to use vanilla JavaScript to get and display the width and height of the box. This information will be updated automatically as needed (for example, when the window gets resized) by using ResizeObserver.

Here’s how it works:

The Code

The full source code (including HTML, CSS, and JavaScript) with explanations:

<!DOCTYPE html>
<html>

<head>
    <style>
        /* Style the orange box */
        .box {
            width: 50%;
            /* Set the width to 50% of the viewport */
            background-color: orange;
            /* Set the background color to orange */
            padding: 20px;
            /* Set some inner padding */
        }
        #width {
            color: blue;
        }
        #height {
            color: red;
        }
    </style>
</head>

<body>

    <!-- The box -->
    <div class="box">
        <h2>Welcome to Sling Academy</h2>
        <p>Sling Academy is a website about programming and data science. These things are invaluable skills to have in
            today’s economy. By learning programming and data science, you can give yourself a competitive edge in the
            job market and open up a world of opportunities.</p>
    </div>

    <!-- display the width and height of the box -->
    <div id="result">
        <h2 id="width"></h2>
        <h2 id="height"></h2>
    </div>

    <script>
        // Get the box element by its class name
        const box = document.querySelector(".box");

        // Get the places where the width and height values will be displayed
        const width = document.getElementById("width");
        const height = document.getElementById("height");

        // Define a function that displays the width and height of an element
        const displaySize = (element) => {
            // Get the offsetWidth and offsetHeight properties of the element
            const w = element.offsetWidth;
            const h = element.offsetHeight;

            // Display the width and height values in the h2 elements
            width.textContent = "The width of the box is " + w + " pixels.";
            height.textContent = "The height of the box is " + h + " pixels.";
        }

        // Call the displaySize function once to display the initial size
        displaySize(box);

        // Create a new ResizeObserver object with a callback function
        const resizeObserver = new ResizeObserver(function (entries) {
            // Loop through each entry (there should be only one in this case)
            for (const entry of entries) {
                // Get the target element of the entry (the box)
                const element = entry.target;

                // Call the displaySize function again to display the new size
                displaySize(element);
            }
        });

        // Observe changes in size of the box element using resizeObserver
        resizeObserver.observe(box);
    </script>
</body>

</html>

Conclusion

This article covered everything you need to know about inspecting the width and height of an arbitrary element by using pure JavaScirpt. This knowledge is very important and necessary when building modern, interactive websites and web apps.

If you find errors or anachronisms in the code examples, please let us know by leaving comments. We will review and update them as soon as possible.