This article summarizes the node operation is narrow, specifically refers to the operation on the element node, and does not include other content, as for the text content and attributes of the operation will be left to the next article

The “look up” operations for nodes were summarized in the previous article, and in this article they include creating nodes, modifying nodes, inserting nodes, deleting nodes, replacing nodes, viewing nodes, and copying nodes

Today’s example is illustrated by the following code:

<ul id="users">
  <li class="user">Small A gentleman</li>
  <li class="user">Small C jun</li>
</ul>
Copy the code

We can imagine an application scenario where, based on the above structure, two new “little B” and “little D” are created and inserted into the above list in the order of ABCD

So let’s get started

Create a node

createElement

Creating an Element node relies primarily on the createElement method, which takes a parameter, the name of the tag to be created:

let tempLi = document.createElement('li');
console.log(tempLi); // <li></li>
Copy the code

The tag name is not case sensitive, but it is generally best to use lowercase ~

When an Element is created, its document is set,

Modify the node

Once an empty Element is created, we need to add content to it based on our needs

If we want to add text content, we can use the following methods;

  • innerText
  • textContent

Adding (inserting) nodes is covered in the next section on inserting nodes

innerText

The innerText property is a readable and writable property that manipulates all the text contained in an element, including the text in the subdocument tree. As the value is read through innerText, it concatenates all the text in the subdocument tree in a descending order. When a value is written through innerText, the result is to remove all children of the element and insert a text node containing the corresponding text value

console.log(document.getElementById('users').innerText); // Mr. A, Mr. B
Copy the code

When we write, we remove all the children of the element and add a text node (we can use element.innertext = “to empty an element). Guess what happens when we execute the following code:

let usersEle = document.getElementById('users');
usersEle.innerText = usersEle.innerText;
Copy the code

(Someone would kill you if you wrote such code, ahem!)

textContent

This property is used in much the same way as innerText. The textContent property is similar to innerText and can be read and written. In read mode, returns the text content of the current node and all its descendants. In write mode, the result is to remove all child nodes of the element and insert text nodes containing the corresponding text values

The main difference is that innerText is an Element property while textContent is a Node property and textContent is not compatible with IE9 and below

console.log(document.getElementById('users').textContent); // Mr. A, Mr. B
Copy the code

Insert the node

Once you’ve created the nodes and added the content, it’s time to insert the nodes into their parent nodes, and there’s more than one way to insert the nodes

  • appendChild
  • insertBefore

appendChild

The effect of this method is obvious from its name, which is to append a child node to the end of the node

Usage:

let tempLi = document.createElement('li');
tempLi.innerText = "Little D.";
document.getElementById('users').appendChild(tempLi);
Copy the code

Since this method can only add nodes to the end of the parent node, it is necessary to pay attention to the order when using it. The usual practice is to do some sort before calling this method

⚠️ Note: If the node to be added already exists in the document, and is not a newly created element, what happens is not simply an insert, but a “move”.

<! -- html body -->
<ul id="users">
  <li class="user">Small A gentleman</li>
  <li class="user">Small C jun</li>
</ul>
<script>
  document.getElementById('users').appendChild(
    document.getElementsByClassName('user') [0])</script>
Copy the code

insertBefore

The insertBefore() method takes two arguments: the node to insert and the reference node. After inserting a node, the inserted node becomes the previousSibling of the reference node and is returned by the method. If the reference node is null, the insertBefore() and appendChild() methods perform the same operation

Similarly, if the inserted node is already part of the document, the result is to move the node from its original location to a new location

This method is more suitable for the insertion of “little B”

let tempLi = document.createElement('li');
tempLi.innerText = "Mr. B.";
document.getElementById('users').insertBefore(
  tempLi,
  document.getElementsByClassName('user') [1]);Copy the code

Remove nodes

removeChild

The removeChild method takes a parameter, the node to be removed, and the removed node becomes the return value of the method

let user0 = document.getElementsByClassName('user') [0];
document.getElementById('users').removeChild(user0);
Copy the code

remove()

The remove method is unusual and can be used directly on the current node to remove the node, with no return value

All you need to do to achieve the same effect is

document.getElementsByClassName('user') [0].remove();
Copy the code

Replace the node

replaceChild

The two arguments replaceChild receives are the node to be inserted and the node to be replaced, which is returned by this method and removed from the document tree, with the node to be inserted taking its place

let tempLi = document.createElement('li');
tempLi.innerText = "Replace node";
document.getElementById('users').replaceChild(
  tempLi,
  document.getElementsByClassName('user') [0]);Copy the code

Copy the node

cloneNode

The cloneNode method is used to clone a node

The caller is the node to be copied, and the return value is a copy of the node

It takes a Boolean value as an argument to indicate whether to perform a deep copy. When the argument is true, deep replication is performed, that is, copying nodes and the entire tree of child nodes. In the case of false, a shallow copy is performed, that is, copying the node itself

let dupUsers = document.getElementById('users').cloneNode(true);
console.log(dupUsers);
Copy the code

⚠️ Note: The default parameters of cloneNode methods vary from specification to specification, so be sure to add parameters

innerHTML

All of these problems can be solved with innerHTML

This method is very similar to innerText in the previous article

  • In read mode, returns the HTML string corresponding to all child nodes of the calling element (including elements, comments, and text nodes);
  • In write mode, innerHTML creates a new DOM tree based on the specified value, and then completely replaces all of the child nodes of the calling element with the DOM tree

We can fetch the node or its parent in read mode, manipulate it using string manipulation, and then write

But we don’t usually do that

Because it has security issues, innerHTML doesn’t check the code and runs directly, which is risky

Therefore, the innerHTML method is recommended to be used only for new nodes, such as creating inserts, preferably with controllable content rather than user-filled content