Javascript offsetWidth returning undefined
Asked Answered
M

1

5

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?

Mirk answered 19/8, 2013 at 15:44 Comment(0)
C
11

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];
Catchascatchcan answered 19/8, 2013 at 15:44 Comment(1)
Ah! Perfect. I'm rather new to JS, missed that part. Thank you.Mirk

© 2022 - 2024 — McMap. All rights reserved.