WeAreRight WeAreRight -4 years ago 126
Javascript Question

getElementsByTagName() applying two times don't work

<ul id="nav">
Favorite beverages :
<li> Tea </li>
<li> Coffee </li>
<li> Milk </li>
</ul>


I want total number of 'li' from 'ul'

Method 1 : It doesn't work

var val = document.getElementsByTagName("ul").getElementsByTagName("li");
console.log(val.length);

Method 2 : It works

var val = document.getElementById("nav").getElementsByTagName("li");
console.log(val.length);


Why Method 1 don't work?

Answer Source

Because document.getElementsByTagName("ul") returns a live HTMLCollection of elements with the given tag name.

For your understanding:

element.getElementsByTagName("li") is valid method.

elements.getElementsByTagName("li") is not a valid method.

var val = document.getElementsByTagName("ul")[0].getElementsByTagName("li");
console.log(val.length);


var val = document.getElementById("nav").getElementsByTagName("li");
console.log(val.length);
<ul id="nav">
  Favorite beverages :
  <li> Tea </li>
  <li> Coffee </li>
  <li> Milk </li>
</ul>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download