Search code examples
javascriptwidthconsole.log

How to get width value of an element with clientWidth?


I am not able to return the value of the width of an element.

let dimensionPopup1 = popup.getElementsByTagName("img");
console.log(dimensionPopup1.clientWidth);

It's returning me "undefined" in the console. Same with offsetWidth, scrollWidth, and width. When I check dimensionPopup1 in my console, I see all the elements and their values. What am I doing wrong?


Solution

  • getElementsByTagName returns an array of elements, so you must access the individual elements within the array to get to their properties.

    For example...

    var items = document.getElementsByTagName("div");
    Array.prototype.forEach.call(items, x => console.log(x.clientHeight));
    <div>A</div>
    <div>B<br/>B</div>
    <div>C<br/>C<br/>C</div>