Following my code:
HTML:
JavaScript
x
5
1
<ul id="ul_o">
2
<li>v1</li>
3
<li>v2</li>
4
</ul>
5
JS:
JavaScript
1
2
1
console.log(document.getElementById("ul_o").getElementsByClassName("LI").length);
2
Why the in the console there are the number 0 instead of 2?
Advertisement
Answer
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 –
JavaScript
1
20
20
1
<html>
2
<head>
3
<title>Test</title>
4
</head>
5
<body>
6
<ul id="ul_o">
7
<li>v1</li>
8
<li>v2</li>
9
<li>v3</li>
10
</ul>
11
<script type='text/javascript'>
12
document.onreadystatechange = function () {
13
if (document.readyState === "interactive") {
14
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>';
15
}
16
}
17
</script>
18
</body>
19
</html>
20