What is the difference between HTMLCollection, NodeList and Object?

2

Sometimes I end up needing to manipulate a NodeList , others an Object but I do not understand exactly what the difference between them is. And what is the relationship of DOM with them?

    
asked by anonymous 04.06.2018 / 19:27

2 answers

1
The DOM (Document Object Model) has several objects, such as window that represents a browser window, and document representing the content of the page.

Within these objects, there may be object lists, which are NodeLists . For example, document can have a list of input objects, a table can have a list of tr objects and so on.

According to the Mozilla documentation ( link ) :

  

NodeList objects are collections of object-like nodes   returned by methods Node.childNodes e    document.querySelectorAll() .

That is, collections of objects. Therefore, DOM is made up of objects, which can contain NodeList from other objects.

Example:

var parent = document.getElementById('divComParagrafos');
// pega todos os "filhos", incluindo espaços
var child_nodes = parent.childNodes;
console.log("child_nodes.length: " + child_nodes.length);

for(var x=0; x < child_nodes.length;x++) {
  console.log(child_nodes[x].innerHTML);
}


// pega todos os nodes de "p"
var nodes = document.querySelectorAll("p")
console.log("nodes.length=" + nodes.length);
for(var x=0; x < nodes.length;x++) {
  console.log(nodes[x].innerHTML);
}
<div id="divComParagrafos">
    <p>Paragravo 1</p>
    <p>Paragravo 2</p>
</div>

HTMLCollection is an array of objects that appear in the HTML document. According to the Mozilla reference ( link ):

  

The HTMLCollection interface represents a generic collection (object   array) of elements (in the order they appear in the document)

    
04.06.2018 / 19:34
0

Referring to link , we can say that:

  • The NodeList object is a list of elements extracted from the html document. Example:

    <title>Card Test</title> 
    <link type="text/css" rel="stylesheet" href="card.css">
    

    <div class= "card-area" id = "card1">
    
        <div clas="card" id="card-1">
    
            <div class = "front" id = "card1-front"> </div>
    
            <div class = "back" id = "card1-back"> <img src = "img-1.png">  </div>
    
        </div>
    
        <div clas="card" id="card-2">
    
            <div class = "front" id = "card2-front"> </div>
    
            <div class = "back" id = "card2-back"> <img src = "img-1.png">  </div>
    
        </div>      
    
    </div>
    <script src="card.js"> </script>
    

If in my script card.js I write the following command var cards  = document.getElementsByClassName ("card") The result would be a nodeList containing all nodes identified with the class card.

  • HTMLColection is a collection of HTML elements (div, p, a, img, etc ...), since the NodeList is a collection of nodes, as in the example above, each card is a node of the nodeList cards .
04.06.2018 / 19:40