Home >Web Front-end >JS Tutorial >How to add nodes in JavaScript

How to add nodes in JavaScript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-04-16 17:34:0113007browse

How to add nodes in JavaScript: 1. Use appendChild(), the syntax is "parent node.appendChild(node ​​to be added)"; 2. Use insertBefore(), the syntax is "parent node.insertBefore(to be added)" Inserted node, insertion position)".

How to add nodes in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

There are 2 ways to add nodes in JS

1. appendChild()

Add the node to be added to the end of the specified parent, so it is also called append

Usage: parent node.appendChild(node ​​to be added)

Code:

document.onclick = function(){
    oDiv2.appendChild(oB2);//将b2追加到div2里面的最后面
}

Illustration:

How to add nodes in JavaScript

2. insertBefore()

The inserted node is added to the specified node in the specified parent before

Usage method: parent node.insertBefore(node ​​to be inserted, specified node)

JS code: (Note: Each execution When a new method is added, the previous method will be commented out. For ease of understanding, it will be commented here once. The code that commented out the previous method will not be posted in the following article)

document.onclick = function(){
    //oDiv2.appendChild(oB2);此处将上一个方法注释
    oDiv2.insertBefore(oB2,oSpan2);//将b2插入到div2中的span2前面
}
Picture Display:

How to add nodes in JavaScript

All browsers support this method, but it is worth noting that if the second parameter node does not exist, it will be replaced under IE and Safari. The node to be added is appended to the specified parent using the appendChild() method, but other mainstream browsers (Firefox, Chrome, Opera, etc.) will report an error, so when inserting a node, you need to first determine whether the second parameter node exists.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to add nodes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn