Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript offsetWidth returning undefined

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?

like image 803
chazbot7 Avatar asked Dec 25 '22 22:12

chazbot7


1 Answers

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];
like image 184
epascarello Avatar answered Dec 28 '22 11:12

epascarello