Skip to main content

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 whouldshould 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 reasonsreason why it's not working?

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 whould 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 work. Any reasons it's not?

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?

Source Link
chazbot7
  • 596
  • 3
  • 13
  • 35

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 whould 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 work. Any reasons it's not?