Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check how many <li> there are in a <ul> with javascript

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?

like image 525
user2992868 Avatar asked Jan 30 '26 23:01

user2992868


1 Answers

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

like image 161
Ishank Avatar answered Feb 02 '26 11:02

Ishank



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!