How do nodes work in javascript?

Asked

Viewed 48 times

0

In many posts I read that in javascript manipulates element gift, also cited as "nodes"

How is the process of manipulation of these nodes ?

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

1 answer

5

THE GIFT (Document Object Model, or "document" object template) is actually a separate API, present in browsers, but not part of the Javascript language itself.

The structure is very simple, it’s 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 that represents this gift would be like this

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

There are several types of knots in the DOM: element nodes (such as div and a), text nodes (within some other element), comment nodes, we represent element attributes, among others.

In the API, each DOM node is represented as an object, with several properties and methods. Among the main ones, I would highlight firstChild (first child node of an element) and nextSibling (next node at the same element level), as only with them is it possible to traverse the entire tree using a recursive style function 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>

  • thanks for the reply, in Debugger to see how it works, I see #text, this #text is an object or it is itself a string?

  • It is an object, a text Node. #text is how the console represents this object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.