Home >Web Front-end >JS Tutorial >How to add a new element node in js? (Detailed explanation with pictures and text)
How to add a new element node in js? This article will introduce to you how to add new nodes of elements in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
To add a new element node in js, you must first create a new element node, and then add the new element node to the html page. Below we use a simple code example to learn more about how JavaScript adds new nodes to elements.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js添加元素新节点</title> <style> #div{ width: 200px; height: 150px; border: 2px solid red; margin: 50px auto; padding: 10px; } </style> </head> <body> <div id="div"> <p id="p1">这是一个段落</p> <p id="p2">这是另一个段落</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("这是一个新的段落。"); para.appendChild(node); var element = document.getElementById("div"); element.appendChild(para); </script> </body> </html>
Rendering:
Let’s analyze it:
1, document.createElement("p") Indicates the creation of a new p tag node (the third p tag);
document.createTextNode() Indicates the creation of a new text content node: this is a new paragraph.
2. Use para.appendChild(node);Add the created text content (node) to the created new p tag (node);
Use appendChild(para) to add (insert) the created p tag (node) and its content (node) into the box with id="div" and display it on the html page.
Summary: The above is the entire content of how to add new elements to js. I hope it will be helpful to everyone's learning. For more related tutorials, please visit JavaScript Video Tutorial, jQuery Video Tutorial, bootstrap Tutorial!
The above is the detailed content of How to add a new element node in js? (Detailed explanation with pictures and text). For more information, please follow other related articles on the PHP Chinese website!