JavaScript HTML DOM elements
Create a new HTML element
Create a new HTML element
To add a new element to the HTML DOM, you must first create the element (an element node), and then append the element to an existing element.Examples
<P id = "p1"> This is a paragraph. </ P>
<P id = "p2"> This is another paragraph. </ P>
</ Div>
<Script>
var para = document.createElement ( "p");
var node = document.createTextNode ( "This is a new paragraph.");
para.appendChild (node);
var element = document.getElementById ( "div1");
element.appendChild (para);
</ Script>
try it"
Examples of analysis:
This code creates a new <p> element:
To add text to the <p> element, you must first create a text node. This code creates a text node:
Then you must add this text node to the <p> element:
Finally, you must add this new element to an existing element.
The code to find an existing element:
The following code after the existing elements add a new element:
Remove the existing HTML elements
The following code demonstrates how to delete elements:
Examples
<P id = "p1"> This is a paragraph. </ P>
<P id = "p2"> This is another paragraph. </ P>
</ Div>
<Script>
var parent = document.getElementById ( "div1");
var child = document.getElementById ( "p1");
parent.removeChild (child);
</ Script>
try it"
Examples of analytical
The HTML document containing the child nodes have two (two <p> element) of the <div> element:
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>
Find id = "div1" elements:
Find id = "p1" the <p> element:
Remove from the parent element sub-elements:
If you can remove an element without a reference to the parent element, it would be great. But unfortunately. DOM elements that you need to know to be deleted, as well as its parent element. |
This is a common solution: find the child element you want to delete, and then use its properties to find parentNode parent element:
child.parentNode.removeChild(child);
HTML DOM Tutorial
In the HTML DOM part of our JavaScript tutorial, you have learned:
- How to change the content of the HTML element (innerHTML)
- How to change the style of HTML elements (CSS)
- How to react to events on the HTML DOM
- How do I add or remove HTML elements
If you want to learn more about using JavaScript to access the HTML DOM knowledge, please visit our complete HTML DOM tutorial .