Home > Web Front-end > JS Tutorial > js dynamically manipulate DOM node method

js dynamically manipulate DOM node method

小云云
Release: 2018-03-16 16:38:26
Original
2037 people have browsed it

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>
Copy after login

Browser effect

js dynamically manipulate DOM node method

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>
Copy after login

Browser effect

js dynamically manipulate DOM node method

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>
Copy after login

js dynamically manipulate DOM node method

Browser rendering

js dynamically manipulate DOM node method

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template