Javascript offsetWidth returns 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 does not start until the page loads:

 <body onload="getWidth()"> 

And a div is defined in CSS as a percentage, with a maximum width of 900 pixels, which should be the result. But instead, I get this warning:

 The width of the contents width padding: undefinedpx. 

I was looking for an answer, but it looks like it should be work. For what reason does it not work?

+4
source share
1 answer

getElementsByClassName returns a collection of nodes.

You act as if this is one thing.

You will need to select an index.

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

Source: https://habr.com/ru/post/1497834/


All Articles