The Document Object Model (DOM) is a standard programming interface recommended by the W3C organization for processing extensible markup languages. On a web page, the objects that organize the page (or document) are organized in a tree structure. The standard model used to represent the objects in the document is called DOM. In this chapter, we will share with you how to add or delete HTML dom elements. Tutorial, come and learn now.
Create a new HTML element
To add a new element to the HTML DOM, you must first create the element (element node ), and then appends the element to an existing element.
<div id="div1"> <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("div1"); element.appendChild(para); </script>
This code creates a new
element:
var para=document.createElement("p");
To add text to a
element, you must first create a text node. This code creates a text node:
var node=document.createTextNode("这是一个新段落。");
Then you have to append the text node to the
element:
para.appendChild(node);
Finally you have to append the new element to an existing element .
This code finds an existing element:
var element=document.getElementById("div1");
The following code adds a new element after an existing element:
element.appendChild(para);
Delete existing HTML Element
<div id="div1"> <p id="p1">这是一个段落。</p> <p id="p2">这是另一个段落。</p> </div> <script> var parent=document.getElementById("div1"); var child=document.getElementById("p1"); parent.removeChild(child); </script>
It would be nice if you could delete an element without referencing the parent element.
But it’s a pity. The DOM needs to know the element you need to delete, and its parent element.
This is a common solution: find the child element you wish to remove, and then use its parentNode attribute to find the parent element:
var child=document.getElementById("p1"); child.parentNode.removeChild(child);
The above is a related tutorial on adding or removing HTML dom elements , hope it can help everyone.
Related recommendations:
How to use DOM to allocate events
The difference between empty and remove in DOM node deletion
jQuery’s method of manipulating DOM
The above is the detailed content of Add or remove HTML dom elements. For more information, please follow other related articles on the PHP Chinese website!