Home >Web Front-end >JS Tutorial >Detailed graphic explanation of how to create nodes and add nodes in JS
JavaScript is often used in front-end development, so do you know how to add child nodes using JS? This article will tell you how to create nodes and add nodes in JS. Friends who are interested can refer to it. I hope it can help you.
To add a new element to the HTML DOM, we must first create the node (that is, the element), and then add it to the location where it needs to be added.
The key to adding nodes is to use the appendChild() method, which can add new child nodes at the end of the child nodes.
Example: The list displays three of the four beauties in ancient times. Click the Add button to add Wang Zhaojun to the list as the last node.
Detailed explanation of steps
The first step is to create a new
The second step, because there is content in the
Step three, use appendChild to add the text node to the
Step four, add the created node to the specified location
var element= document.getElementById("myList") finds an existing element
element.appendChild(node) appends a new element to an existing element
The complete code is as follows
HTML part:
<body> <ul id="myList"> <li>杨玉环</li> <li>西施</li> <li>貂蝉</li> </ul> <p>单击按钮将项目添加到列表中</p> <button onclick="myFunction()">点击添加</button> </body>
JavaScript part:
<script type="text/javascript"> function myFunction(){ var node=document.createElement("li"); var textnode=document.createTextNode("王昭君"); node.appendChild(textnode); document.getElementById("myList").appendChild(node); } </script>
Rendering:
##First picture It is the effect without adding nodes. The second picture is the effect after clicking to add nodes, adding Wang Zhaojun to HTML. The above introduces the method of creating nodes and adding 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 visitThe above is the detailed content of Detailed graphic explanation of how to create nodes and add nodes in JS. For more information, please follow other related articles on the PHP Chinese website!