Home > Article > Web Front-end > Detailed graphic explanation of how to delete nodes in JavaScript
JavaScript is often used in front-end development, so do you know how to delete the tail node using JS? This article will tell you how to delete nodes by clicking on JS and how to delete the first node in JS. Friends who are interested can refer to it. I hope it can help you.
To delete a node, we must first find the node to be deleted and its parent element, and then use removeChild to delete the child element from the parent element.
Example: The list lists the four major accounting firms. Delete the first node of the list, which is PricewaterhouseCoopers, by clicking the button.
HTML part:
<ul id="myList"> <li id="li1">普华永道(PwC)</li> <li id="li2">德勤(DTT)</li> <li id="li3">毕马威(KPMG)</li> <li id="li4">安永(EY)</li> </ul>
Detailed explanation of steps:
The first step is to find the element with id="myList", that is,
The second step is to find the
The third step, use removeChild to delete the child element from the parent element
list.removeChild(li)
Note: DOM must know which element needs to be deleted and its parent element
Another method (same principle): first find the child element that needs to be deleted, and then use the parentNode attribute to find its parent element. The code is as follows:
var li=document.getElementById("li1");
li.parentNode.removeChild(li);
JS can not only delete the first node, but also delete the tail node, and Any node you want to delete, just find the location of the corresponding node.
The complete code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <ul id="myList"> <li id="li1">普华永道(PwC)</li> <li id="li2">德勤(DTT)</li> <li id="li3">毕马威(KPMG)</li> <li id="li4">安永(EY)</li> </ul> <p>单击按钮删除列表中的第一个元素</p> <button onclick="myFunction()">点击删除</button> </body> <script type="text/javascript"> function myFunction(){ var list=document.getElementById("myList"); var li=document.getElementById("li1"); list.removeChild(li); } </script> </html>
Rendering:
The first picture is without deleting the node Effect, the second picture is the effect after deleting the first node.
The above mainly introduces how to delete nodes in JS. It is relatively detailed and easy to understand. Beginners can try it by themselves. I hope this article will be helpful to you! For more related tutorials, please visit JavaScript Video Tutorial php Public Welfare Training
The above is the detailed content of Detailed graphic explanation of how to delete nodes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!