JavaScript node operation

Node overview

All contents in a web page are nodes (labels, attributes, text, comments, etc.), and nodes are represented by nodes in DOM.

All nodes in the HTML DOM tree can be accessed through JavaScript, and all HTML elements (nodes) can be modified, created or deleted.

Generally, a node has at least three basic attributes: nodeType, nodeName, and nodeValue.

Node level

Using DOM tree, nodes can be divided into different hierarchical relationships. The common hierarchical relationship is parent-child brother.

Parent node

node.parentNode

The return value is the nearest parent node (parent)
If the specified node has no parent node, null needs to be returned

<div class="demo">
        <div class="box">
            <span class="erweima">×</span>
        </div>
    </div>
    <script>
        // 1. Parent node
        var erweima = document.querySelector('.erweima');
        // var box = document.querySelector('.box');
        // The result is the parent node nearest to the element (parent). If the parent node cannot be found, it will return null
        console.log(erweima.parentNode);
    </script>

Child node

All child nodes

parentNode.childNodes(standard)

parentNode.childNodes returns a collection of child nodes containing the specified node
This collection is a collection of immediate updates
Note: the return value contains all child nodes, including element nodes, text nodes, etc;
If you only want to get the element nodes inside, you need special processing, so we generally do not advocate using childNodes

Child element node

parentNode.children(Nonstandard)

parentNode.children is a read-only attribute that returns all child element nodes. It only returns child element nodes, and other nodes do not
Although children is a non-standard, it is supported by various browsers
So we can use it safely
The case is as follows

  <ul>
        <li>I am li</li>
        <li>I am li</li>
        <li>I am li</li>
        <li>I am li</li>
    </ul>
    <script>
        // Method provided by API (DOM)
        var ul = document.querySelector('ul');
        var lis = ul.querySelectorAll('li');
        // Child nodes of all child nodes, and so on
        console.log(ul.childNodes);
        console.log(ul.childNodes[0].nodeType);
        console.log(ul.childNodes[1].nodeType);
        // 2. children's access to all sub element nodes is also commonly used in our actual development
        console.log(ul.children);
    </script>

First child node

parentNode.firstChild

Returns null if the first child node cannot be found
It also contains all nodes

Last child node

parentNode.lastChild

Returns the last child node. If it cannot be found, it returns null
It also contains all nodes

First element node

parentNode.firstElementChild

Returns the first child element. If the node cannot be found, null is returned

Last element node

parentNode.lastElementChild

Returns the last child element. If the node cannot be found, null is returned

Commonly used

In the actual development, firstChild and lastChild contain other nodes, which is inconvenient to operate, and firstElementChild and lastElementChild have compatibility problems, so how can we obtain the first child element node or the last child element node?
Solution
If you want the first child element node
You can use parentnode children[0];
If you want the last child element node
You can use parentnode children[parentNode.children.length-1];

Sibling node

Next sibling node

 node. nextslibling Get the next sibling element. If there is no node, return null
``

```javascript
 node.nextElementSibling Get the next sibling element. If there is no node, return null

Previous sibling node

node.previousElementSibling 

Returns the previous sibling node of the current element. If it cannot be found, null is returned

Create node

documen.createElement(Node name created')

documen. The createElement () method creates the HTML elements specified by tagName. Because these elements did not exist originally and were generated dynamically according to our requirements, we also call them dynamic creation element nodes

Add node

node.appendChild(child)

node. The appendChild () method adds a node to the end of the child node list of the parent node, which is similar to the after pseudo element in css

node.insertBefore(child,Specify element)

node. The insertBefore () method adds a node to the specified child node of the parent node, which is similar to the before pseudo element in css.

Delete node

node.removeChild() 

node. The removechild () method deletes a child node from the node node
Returns the deleted node

<button>delete</button>
<ul>
    <li>Xiong Da</li>
    <li>Xiong er</li>
    <li>Bald head strength</li>
</ul>
<script>
    // 1. Get element
    var ul = document.querySelector('ul');
    var btn = document.querySelector('button');
    // 2. Delete the element node removeChild(child)
    // ul.removeChild(ul.children[0]);
    // 3. Click the button to delete the children in turn
    btn.onclick = function() {
        if (ul.children.length == 0) {
            this.disabled = true;
        } else {
            ul.removeChild(ul.children[0]);
        }
    }
</script>

Clone node

node. The cloneNode () method returns a copy of the node that called the method
Also known as clone node / copy node
It should be noted that
If the bracket parameter is empty or false, it is a shallow copy, that is, only clone the replicated node itself, not the child nodes inside

If the parenthesis parameter is true, the deep copy will copy the node itself and all its child nodes

Three ways to create elements

document.write()

document.write() creates an element. If the page document stream is loaded, calling this sentence again will cause the page to be redrawn
It can be understood as coverage

innerHTML

Low efficiency
Writing content to a DOM node does not cause the page to be redrawn entirely
innerHTML is more efficient in creating multiple elements and slightly more complex in structure
innerHTML array mode (high efficiency)

creatElement()

Average efficiency
creatElement () creates multiple elements, which is a little less efficient, but the structure is clearer

Keywords: Javascript Front-end

Added by laide234 on Sun, 13 Feb 2022 15:40:16 +0200