This article mainly shares with you the js method of dynamically manipulating DOM nodes. It mainly uses js to control adding and deleting DOM nodes and deleting DOM nodes. I hope it can help everyone.
js control to add and delete DOM nodes
1. Add dom node
<p id="p1"> <p id="p_1">我是第一个段落</p> <p id="p_2">我是第二个段落</p> </p>
Browser effect
Start writing js code
<script> /*创建一个元素节点*/ var arr=document.createElement("p"); /*给元素增加文本节点*/ var txt=document.createTextNode("这是添加的文本"); /*把文本节点追加到元素节点上*/ arr.appendChild(txt); /*找到一个存在的元素节点*/ var par=document.getElementById("p_1"); /*把新的元素节点追加到已存在的元素节点上*/ par.appendChild(arr);</script>
Browser effect
You can find the parent element and add nodes. You can also find sibling elements to add nodes. When searching for a parent element, the newly added element will be added at the end of all elements. When searching for a sibling element, the newly added element will be added after the selected element by default. This should be noted.
2. Delete DOM nodes
To delete an HTML element, you must first obtain the parent element of the element:
<p id="p1"> <p id="p_1">我是第一个段落</p> <p id="p_2">我是第二个段落</p> </p>
Browser rendering
Okay, done, thank you for watching.
Related recommendations:
Summary of native JavaScript operations on dom nodes
Summary of DOM node operation methods in jQuery
Example sharing JQuery selector and DOM node operation exercises
The above is the detailed content of js dynamically manipulate DOM node method. For more information, please follow other related articles on the PHP Chinese website!