This is the 12th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

This is the forty-second article in the Learn Front End from Scratch series – Node Objects

This series of articles in the nuggets first, preparation is not easy to reprint please obtain permission

An overview of the

What is a Node object

The DOM standard specification provides Node objects, which provide properties and methods for parsing the DOM Node tree structure.

DOM tree structure mainly depends on nodes for parsing, called DOM node tree structure. The Node object is the main entry point for parsing the DOM Node tree structure.

The Node object provides properties and methods for traversing nodes, inserting points, and replacing nodes.

Unlike the Document object, Node objects do not provide objects that can be used directly and do not allow object creation with the new keyword.

The page element that we located earlier is actually a Node object, called a Node element; And the self-created Node, which is also a Node object.

Example code is as follows:

<body>
  <button id="btn">button</button>
  <script>
    var btn = document.getElementById('btn')
    // Locate the page elements that are Node objects, called Node elements
    console.log(btn instanceof NOde)//true
    // Self-created nodes are Node objects
    var button = document.createElement('button')
    console.log(button instanceof Node)//true
    // Get all its attributes and methods
    console.log(Node.prototype)
  </script>
</body>
Copy the code

Inheritance chain relation

The Node object inherits from the EventTarget object, which is an object used to receive events.

The Document object and Element object in the DOM standard specification are both derived from Node objects.

The test code is as follows

<body>
  <script>
    console.log(Node.prototype instanceof EventTarget)//true

    console.log(Document.prototype instanceof Node)//true
    console.log(Element.prototype instanceof Node)//true
  </script>
</body>
Copy the code

Determining the Node type

The Node object provides nodeName(read-only), nodeType(read-only), and nodeValue, which can be used to obtain the Node name, Node type, and Node value of a specified Node, respectively.

In the DOM node tree structure, the most common nodes we actually developed are:

The name of the node meaning The correspondingnodeTypevalue
Element nodes Represents a tag in an HTML page (that is, the structure of an HTML page) 1
Text node Represents the text content contained by a tag in an HTML page 3
An attribute node Represents the attribute contained in the start tag of an HTML page 2

The sample code looks like this:

The HTML structure is as follows:

<button class="cls" id="btn">button</button>
Copy the code

Element nodes

var btnElement = document.getElementById('btn')

console.log(btnElement.nodeName)  // BUTTON
console.log(btnElement.nodeType)  / / 1
console.log(btnElement.nodeValue) // null
Copy the code

The nodeName attribute value of the element node is the tag name (uppercase)

Text node

It is known from the DOM structure tree that the text node belongs to the child node of the element node

We can use the Node.firstChild property (read-only) to get its children, or null if the Node has no children.

var textNode = btnElement.firstChild

console.log(textNode.nodeName)  // #text
console.log(textNode.nodeType)  / / 2
console.log(textNode.nodeValue) / / button
Copy the code

The nodeName attribute of the text node has a fixed value of #text

NodeValue is not a read-only property, which means we can not only get it, but also modify it, as shown in the following code

Textnode. nodeValue = 'New button'Copy the code

An attribute node

The attribute node is not a child or sibling, and we can get the attribute node using the element.getAttributenode () method

Function: Returns the specified attribute node of the specified element.

The syntax is as follows:

var attrNode = element.getAttributeNode(attrName);
Copy the code
  • attrName: a string containing the name of the property
var attrNode = btnElement.getAttributeNode('class')

console.log(attrNode.nodeName)  // class
console.log(attrNode.nodeType)  / / 2
console.log(attrNode.nodeValue) // cls
Copy the code

The nodeName of the attribute node is the attribute name of the current element

The nodeValue attribute of the property node is the value corresponding to the current property name, which can be modified

Traverse the nodes

Here the so-called traversal node refers to: according to the node tree structure to obtain nodes. From the node tree, we know that there are three levels of relationship in the node tree, namely, ancestor and offspring, parent and child, and brother relationship. Ancestor and offspring can be replaced by parent and child. So what we’re learning here is how do we get a parent node, a child node, an adjacent sibling node

Get the parent node

To find the parentNode using the specified element in the HTML page, we can use the parentNode property of the Node object, which has the following syntax structure

var parentNode = node.parentNode
Copy the code
  • parentNode: Specifies the parent of a node. The parent of an element node may be an elementElementNode, which can also be a documentDocumentnode

Example code is as follows:

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>huawei</li>
  </ul>
  <script>
    // as a child node
    var mi = document.getElementById('mi')
    // Get the parent node from the child node
    var parent1 = mi.parentNode
    console.log(parent1)// ul
  </script>
</body>
Copy the code

Similar to the parentNode attribute, there is a parentElement attribute that returns the parentNode of the current node, or null if the element has no parent or if the parent is not a DOM element.

There is no difference between operating on < HTML > nodes, but there is a difference between operating on < HTML > tags, as shown in the following code

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>huawei</li>
  </ul>
  <script>
    //< HTML > as a child node
    var html = document.documentElement
    // Get the parent node from the child node
    console.log(html.parentNode)// Document node
    console.log(html.parentElement)// null
  </script>
</body>
Copy the code

Get child/blank node problem

To find its child nodes by executing elements in an HTML page, we can do this through the following Node object properties

The property name describe
Node.childNodes Gets all children of the specified node
Node.firstChild Gets the first child of the specified node
Node.lastChild Gets the last child of the specified node

Sample code is as follows

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>The hammer</li>
  </ul>
  <script>
    var parent = document.getElementById('parent')
    // The childNodes property - gets all the children of the specified node
    var children = parent.childNodes
    console.log(children) // NodeList(7) [text, li, text, li#mi, text, li, text]
  </script>
</body>
Copy the code

Most browsers have a problem with fetching directly, because we only have three text nodes, we get seven, and the four extra results are text nodes, so the text nodes with no content become blank nodes.

So where are these text nodes? When we write OUR HTML code, we add line breaks and Spaces for readability, and these Spaces and line breaks are text content.

The blank node problem is illustrated below

We know that all blank nodes are text nodes, and the value of the text node nodeType is 3, while the value of the element node nodeType is 1. We can solve this problem by using loop plus judgment. Sample code is as follows

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>The hammer</li>
  </ul>
  <script>
    var parent = document.getElementById('parent');
    // The childNodes property - gets all the children of the specified node
    var children = parent.childNodes;
    console.log(children);

    // Used to access the real byte set
    var arr = []
    for (var i = 0; i < children.length; i++) {
      var child = children[i]
      if (child.nodeType === 1) {
        The array.push () method is used to append data to an Array
        arr.push(child)
      }
    }
    console.log(arr)// Array(3)
  </script>
</body>
Copy the code

Gets adjacent sibling nodes

We can use the following Node object attributes to find neighboring sibling nodes by specifying elements in the HTML page:

The property name describe
Node.nextSibling(read-only) Returns the next sibling of the current node, or if there is nonenull.
Node.previousSibling(read-only) Returns the previous sibling of the current node, or nonenull.

Sample code is as follows

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>The hammer</li>
  </ul>
  <script>
    var parent = document.getElementById('parent');
    // The childNodes property - gets all the children of the specified node
    var children = parent.childNodes;
    console.log(children);

    // Used to access the real byte set
    var arr = []
    for (var i = 0; i < children.length; i++) {
      var child = children[i]
      if (child.nodeType === 1) {
        The array.push () method is used to append data to an Array
        arr.push(child)
      }
    }
    console.log(arr)// Array(3)
  </script>
</body>
Copy the code

Insert the node

Node. The appendChild () method

The node.appendChild () method appends a Node to the end of the list of children of the specified parent Node. If the node to be inserted already exists in the document tree of the current document, appendChild() will simply move it from its original location to the new location (no need to remove the node to be moved beforehand).

The syntax structure is as follows

element.appendChild(aChild)
Copy the code
  • aChild: Node to append to the parent node.

The return value of this method is the child node.

Example code is as follows:

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>The hammer</li>
  </ul>
  <script>
    var parent = document.getElementById('parent')

    // Create a child node
    var newLi = document.createElement('li')
    // Create a text node
    var textNode = document.createTextNode('huawei')
    // Appends the text node to the new child node
    newLi.appendChild(textNode)
    // Append the new child node to the parent node
    parent.appendChild(newLi)
  </script>
</body>
Copy the code

Node. The insertBefore () method

The node.insertbefore () method inserts a child Node with the specified parent before the reference Node. If a given child node is a reference to an existing node in the document, insertBefore() moves it from its current location to a new location. If the reference node is null, the specified node is added to the end of the list of children of the specified parent node.

The syntax structure is as follows

var insertedNode = parentNode.insertBefore(newNode, referenceNode);
Copy the code
  • parentNode: Indicates the parent node of the newly inserted node
  • newNode: node for insertion
  • referenceNode:newNodeIt’s going to be inserted before this node

Return value insertedNode indicates the insertedNode (newNode)

Sample code is as follows

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>The hammer</li>
  </ul>
  <script>
    var parent = document.getElementById('parent')

    // Create a child node
    var newLi = document.createElement('li')
    // Create a text node
    var textNode = document.createTextNode('huawei')
    // Appends the text node to the new child node
    newLi.appendChild(textNode)
    // Get the target node
    var mi = document.getElementById('mi')
    // Insert the new child node before the rice
    parent.insertBefore(newLi, mi)
    // If the node before the node to be inserted is null, it is inserted last by default
    var nli = document.createElement('li')
    var tNode = document.createTextNode('samsung')
    nli.appendChild(tNode)
    parent.insertBefore(nli, null)
  </script>
</body>
Copy the code

Remove nodes

The Node object provides the node.removechild () method to remove a child Node from the DOM. Returns the deleted node.

The syntax is as follows:

var oldChild = node.removeChild(child);
//OR
element.removeChild(child);
Copy the code
  • child: The child node to remove.
  • node:childParent node of.

The return value oldChild holds a reference to the deleted child node, so oldChild and Child are equal.

Note that the child node is still in memory after we delete it, but not added to the DOM tree of the current document, so we can insert the node back into the document, but only if we use a variable to store the deleted return value. If the return value is not stored, the removed node is considered useless and will be reclaimed by memory management in a short time.

This method throws an exception if the Child node is not a child of a Node node.

Sample code is as follows

<body>
  <ul id="parent">
    <li>apple</li>
    <li id="mi">millet</li>
    <li>The hammer</li>
  </ul>
  <script>
    var parent = document.getElementById('parent')
    var mi = document.getElementById('mi')
    var oldChild = parent.removeChild(mi)
  </script>
</body>
Copy the code

Replace the node

The Node object provides the replaceChild() method to replace nodes in HTML pages.

The syntax structure is as follows

var replaceNode = parentNode.replaceChild(newChild, oldChild);
Copy the code

Parameters that

  • parentNodeSaid:oldChildThe parent node of a node.
  • newChild: used to replaceoldChildThe new node of. If the node already exists in the DOM tree, it is first removed from its original location.
  • oldChild: The original node to be replaced.

The return value is the replaced node, replaceNode == oldChild.

The sample code looks like this:

<body>
  <ul id="phone">
    <li>huawei</li>
    <li id="mi">millet</li>
    <li>zte</li>
  </ul>
  <script>
    1. Obtain the parent node of the target node
    var parent = document.getElementById('phone')
    // 2. Obtain the target node
    var mi = document.getElementById('mi')
    Create a node
    var newLi = document.createElement('li')
    var nodeText = document.createTextNode('black shark')
    newLi.appendChild(nodeText)
    / / 4.. To replace
    parent.replaceChild(newLi, mi)
  </script>
</body>
Copy the code

The following information is displayed:

There is another case where the current node already exists and the new node will be deleted from its original position.

Copy the node

The Node object provides the cloneNode() method for copying nodes in HTML pages.

The syntax structure is as follows

var dupNode = node.cloneNode(deep);
Copy the code
  • node: Node to be cloned
  • dupNode: Copy node generated by clone
  • deep(Optional) : Indicates whether to use deep clone. If yes, selecttrue, then all descendants of the node will also be cloned, iffalse(default), only the node itself is cloned.

Sample code is as follows

<body>
  <button>button</button>
  <script>
    // 1. Obtain the node to be replicated
    var btn = document.getElementsByTagName('button') [0]
    // 2. Replicate the node
    var newbtn = btn.cloneNode(true)  // If false, child nodes are not copied
    // 3. Add child nodes to the page
    var body = document.body
    body.appendChild(newbtn)

  </script>
</body>
Copy the code

Note that if a node has an ID attribute, it will be copied together, but the ID attribute is a unique attribute, and this can cause problems.

Write in the last

If you are reading this, I am honored, if you like this article, you can give this article a little like; If you like this column, I will keep updating it to more than 100 posts, you can click on the link at the back to learn from the front – a bowl week column – nuggets (juejin. Cn) after entering to pay attention.

And you can give me a little attention, too.

Phase to recommend

  • Summary of 42 front-end layout schemes – Juejin (juejin. Cn)
  • – Juejin (juejin. Cn)