JavaScript operation DOM

JavaScript operation DOM

Update DOM

After we get a DOM node, we can update it.

You can directly modify the text of a node in two ways:

One is to modify the innerHTML attribute. This method is very powerful. It can not only modify the text content of a DOM node, but also directly modify the subtree inside the DOM node through HTML fragments:

// Get < p id = "p-id" ></ p>
var p = document.getElementById('p-id');
// Set the text to abc:
p.innerHTML = 'ABC'; // <p id="p-id">ABC</p>
// Set HTML:
p.innerHTML = 'ABC <span style="color:red">RED</span> XYZ';
// <p>...</ p> The internal structure of has been modified

When using innerHTML, you should pay attention to whether you need to write HTML. If the written string is obtained through the network, pay attention to character encoding to avoid XSS attack.

The second is to modify the innerText or textContent attribute, so that the string can be automatically HTML encoded to ensure that no HTML tag can be set:

// Get < p id = "p-id" ></ p>
var p = document.getElementById('p-id');
// Set text:
p.innerText = '<script>alert("Hi")</script>';
// HTML is automatically encoded, unable to set a < script > node:
// <p id="p-id">&lt;script&gt;alert("Hi")&lt;/script&gt;</p>

The difference between the two is that innerText does not return the text of hidden elements when reading attributes, while textContent returns all text. Note that IE < 9 does not support textContent.

Modifying CSS is also a frequent operation. The style attribute of the DOM node corresponds to all CSS and can be obtained or set directly. Because CSS allows names such as font size, but it is not a valid property name in JavaScript, it needs to be rewritten as hump named fontSize in javascript:

// Get < p id = "p-id" ></ p>
var p = document.getElementById('p-id');
// Set CSS:
p.style.color = '#ff0000';
p.style.fontSize = '20px';
p.style.paddingTop = '2em';

Insert DOM

When we get a DOM node and want to insert a new DOM into the DOM node, what should we do?

If the DOM node is empty, for example, < div > < / div >, you can directly use innerHTML = '< span > child < / span >' to modify the contents of the DOM node, which is equivalent to "inserting" a new DOM node.

If the DOM node is not empty, you cannot do so, because innerHTML will directly replace all the original child nodes.

There are two ways to insert a new node. One is to use appendChild to add a child node to the last child node of the parent node. For example:

<!-- HTML structure -->
<p id="js">JavaScript</p>
<div id="list">
    <p id="java">Java</p>
    <p id="python">Python</p>
    <p id="scheme">Scheme</p>
</div>

Add < p id = "JS" > JavaScript < / P > to the last item of < div id = "list":

var
    js = document.getElementById('js'),
    list = document.getElementById('list');
list.appendChild(js);

Now, the HTML structure is like this:

<!-- HTML structure -->
<div id="list">
    <p id="java">Java</p>
    <p id="python">Python</p>
    <p id="scheme">Scheme</p>
    <p id="js">JavaScript</p>
</div>

Because the js node we inserted already exists in the current document tree, this node will first be deleted from the original location and then inserted into a new location.

More often, we will create a new node from zero and insert it into the specified location:

var
    list = document.getElementById('list'),
    haskell = document.createElement('p');
haskell.id = 'haskell';
haskell.innerText = 'Haskell';
list.appendChild(haskell);

In this way, we dynamically add a new node:

<!-- HTML structure -->
<div id="list">
    <p id="java">Java</p>
    <p id="python">Python</p>
    <p id="scheme">Scheme</p>
    <p id="haskell">Haskell</p>
</div>

Creating a node dynamically and adding it to the DOM tree can achieve many functions. For example, the following code dynamically creates a < style > node and adds it to the end of the < head > node, thus dynamically adding new CSS definitions to the document:

var d = document.createElement('style');
d.setAttribute('type', 'text/css');
d.innerHTML = 'p { color: red }';
document.getElementsByTagName('head')[0].appendChild(d);

You can execute the above code on the Chrome console to observe the change of page style.

insertBefore

What if we want to insert the child node into the specified location? You can use parentelement insertBefore(newElement, referenceElement);, Child nodes are inserted before referenceelement.

Taking the HTML above as an example, suppose we want to insert Haskell before Python:

<!-- HTML structure -->
<div id="list">
    <p id="java">Java</p>
    <p id="python">Python</p>
    <p id="scheme">Scheme</p>
</div>

It can be written as follows:

var
    list = document.getElementById('list'),
    ref = document.getElementById('python'),
    haskell = document.createElement('p');
haskell.id = 'haskell';
haskell.innerText = 'Haskell';
list.insertBefore(haskell, ref);

The new HTML structure is as follows:

<!-- HTML structure -->
<div id="list">
    <p id="java">Java</p>
    <p id="haskell">Haskell</p>
    <p id="python">Python</p>
    <p id="scheme">Scheme</p>
</div>

It can be seen that the key point of using insertBefore is to get a reference to the "reference child node". In many cases, it is necessary to cycle all child nodes of a parent node, which can be achieved by iterating the children attribute:

var
    i, c,
    list = document.getElementById('list');
for (i = 0; i < list.children.length; i++) {
    c = list.children[i]; // Get the ith child node
}

Delete DOM

Deleting a DOM node is much easier than inserting it.

To delete a node, first obtain the node itself and its parent node, then call the parent node's removeChild to delete itself:

// Get the node to be deleted:
var self = document.getElementById('to-be-removed');
// Get parent node:
var parent = self.parentElement;
// Delete:
var removed = parent.removeChild(self);
removed === self; // true

Note that although the deleted node is not in the document tree, it is still in memory and can be added to other locations at any time.

When you traverse the child nodes of a parent node and delete them, you should note that the children attribute is a read-only attribute, and it will be updated in real time when the child nodes change.

For example, for the following HTML structure:

<div id="parent">
    <p>First</p>
    <p>Second</p>
</div>

When we delete a child node with the following code:

var parent = document.getElementById('parent');
parent.removeChild(parent.children[0]);
parent.removeChild(parent.children[1]); // < -- browser error

Browser error: parent Children [1] is not a valid node. The reason is that when the < p > first < / P > node is deleted, the parent The number of nodes in children has changed from 2 to 1, and the index [1] no longer exists.

Therefore, when deleting multiple nodes, note that the children attribute changes all the time.

Keywords: Javascript Front-end

Added by rish1103 on Mon, 17 Jan 2022 16:08:23 +0200