How do nodes work in javascript?

0

In many posts I read that in javascript manipulates element dom, also referred to as "nodes"

How is the process of manipulating these nodes?

What is the structure involved? What format? Xml style? in tree?

    
asked by anonymous 20.05.2015 / 19:14

1 answer

5

The Document Object Model (DOM), or "document" object model) is actually a separate API in browsers but not part of the JavaScript language itself.

The structure is very simple, it is a tree, and each element is a node ( node ) of that tree.

Take the following HTML as an example:

<body>
    <div>
       <a href="http://example.com">Link</a>
    </div>
</body>

The tree representing this DOM would be like this

document
  - body
    - elemento <div>
      - elemento <a>
        - texto "Link"

There are several node types in the DOM: element nodes (such as div and a ), text nodes (within some other element), comment nodes, nodes that represent element attributes, and so on.

In the API, each DOM node is represented as an object, with several properties and methods . Among the main ones, I would point out firstChild (first child node of an element) and nextSibling (next node at the same level of the element), since with them it is only possible to traverse the entire tree using a depth -first :

function traverse(el) {
    if(el.firstChild) traverse(el.firstChild);
    while(el) {
        console.log(el.nodeName, el.nodeType, el.textContent);
        el = el.nextSibling
    }
}

window.onload = function() {
  traverse(document.body);
}
<div>
    <a href="http://example.com">Link</a>
</div>
    
20.05.2015 / 19:32