Question

I have been working towards understanding the DOM very thoroughly. At the moment i'm making my way trough traversing the DOM tree and i seem to be finding some inconsistencies.

  • a nodeList is returned when i select more than 1 element
  • a HTMLElement is returned when i select only 1 element

So the question is, why does this code return a nodeList, even if i select only 1 li.

See this fiddle for an example: http://jsfiddle.net/AmhVk/5

Could someone explain this to me very thoroughly? Thx...

<ul id="jow">
    <li><a href="">Item</a></li>    
    <li><a href="">Item</a></li>
    <li class="active"><a href="">Item</a></li> 
    <li><a href="">Item</a></li>
    <li><a href="">Item</a></li>
</ul>

<div id="ieps"></div>

function simple(){

var li = document.querySelectorAll(".active");
var ul = li[0].parentNode;
var getULchild = ul.children[0];

var ieps = document.getElementById("ieps");

ieps.innerHTML += "ul will return = " + ul + "<br>";
ieps.innerHTML += "li will return = " + li + "<br><br>";        

ieps.innerHTML += "ul[0] will return: " + ul[0] + "<br>";
ieps.innerHTML += "li[0] will return: " + li[0] + "<br><br>";

}
Was it helpful?

Solution

Correction :

  • a nodeList is returned when you call a function which may select more than 1 element
  • a HTMLElement is returned when you call a function which can select 1 element at most

This way you don't have to test the type of the returned value at each call.

querySelectorAll is designed to return an undefined number of elements, so it returns a nodeList.

On the contrary there's generally no point in returning a nodeList when you use getElementById (as one element at most may have a given id), that's why it directly returns one element (or null).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top