Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 800
David Avatar asked Dec 20 '25 04:12

David


1 Answers

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.

like image 95
cletus Avatar answered Dec 22 '25 17:12

cletus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!