Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  39] [ 2]  / answers: 1 / hits: 54326  / 11 Years ago, mon, november 18, 2013, 12:00:00

Following my code:



HTML:



<ul id=ul_o>
<li>v1</li>
<li>v2</li>
</ul>


JS:



console.log(document.getElementById(ul_o).getElementsByClassName(LI).length);


Why the in the console there are the number 0 instead of 2?


More From » html

 Answers
69

Give - document.getElementById(ul_o).getElementsByTagName(li).length



To have a wider answer that ensures the dom is ready for being accessed and updated by JS, we can make use of the onreadystatechange event something like in html5 -



<html>
<head>
<title>Test</title>
</head>
<body>
<ul id=ul_o>
<li>v1</li>
<li>v2</li>
<li>v3</li>
</ul>
<script type='text/javascript'>
document.onreadystatechange = function () {
if (document.readyState === interactive) {
document.body.innerHTML = '<h4><code>ul</code> with <i>ul_o</i> has '+document.getElementById(ul_o).getElementsByTagName(li).length +' <code>li</code> Tags</h4>';
}
}
</script>
</body>
</html>


Fiddle


[#74234] Friday, November 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions
;