Javascript offsetWidth returning undefined

11.7k views Asked by At

I have a JS function that gets the width of a div on my page:

function getWidth() { 
   var container = document.getElementsByClassName('tag');
   var message = "The width of the contents width padding: " + container.width + "px.\n";
   alert(message);
}

The function doesn't run until page is loaded:

<body onload="getWidth()">

And the div is defined in CSS as a percentage, with a max-width of 900px, which is what the output should be. But instead, I'm getting this alert:

The width of the contents width padding: undefinedpx.

I've looked around for an answer, but it looks like this should be work. Any reason why it's not working?

1

There are 1 answers

1
epascarello On BEST ANSWER

getElementsByClassName returns a collection of nodes.

You are acting like it is one.

You would need to select the index.

var container = document.getElementsByClassName('tag')[0];