David
David

Reputation: 2423

get element after page loads

how do i call a function to count the number of divs with an id of 'd1' after the page loads. right now i have it in my section but doesnt that execute the script before anything in the loads? because it works if i put the code below the div tags...

Upvotes: 3

Views: 13848

Answers (4)

Anthony
Anthony

Reputation: 37065

You need to have the function tied to the onload event, like so:

window.onload = function() {
    var divElements = document.getElementById("d1");
    var divCount = divElements.length;
    alert(divCount);
};

For the record, you should only have one div with that ID, as having more than one is invalid and may cause problems.

Upvotes: 0

Paul Creasey
Paul Creasey

Reputation: 28864

well an ID should be unique so the answer should be one.

you can use <body onload='myFunc()'> to call a script once the DOM is loaded.

Upvotes: 0

mtmk
mtmk

Reputation: 6316

Use jQuery's document.ready() or hook up to the onLoad event.

Upvotes: 0

cletus
cletus

Reputation: 625237

Firstly there should be at most one because IDs aren't meant to be repeated.

Second, in straight Javascript you can call getElementById() to verify it exists or getElementsByTagName() to loop through all the divs and count the number that match your criteria.

var elem = document.getElementById("d1");
if (elem) {
  // it exists
}

or

var divs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0; i < divs.length; i++) { 
  var div = divs[i];
  if (div.id == "d1") {
    count++;
  }
}

But I can't guarantee the correct behaviour of this because like I said, IDs are meant to be unique and when they're not behaviour is undefined.

Upvotes: 3

Related Questions