views:

36

answers:

4

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...

+2  A: 

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.

cletus
ok i have 8 divs, they are positioned absolute, they are inside a parent div, i want the bottom of the child div, to be at the top of the parent div. if that makes sense, so basicly there are 2 divs, the child div on top of the parent div. do you know how i can loop through them to do this? also the child div is dynamic so i cant really do it in css
David
I don't really understand the request but the answer is probably to learn/use jquery :)
Paul Creasey
@David: i don't really understand either but it almost sounds like a separate question.
cletus
A: 

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

Maxwell Troy Milton King
A: 

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.

Paul Creasey
A: 

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.

Anthony