This article describes how to operate HTML elements and styles in JavaScript. you can use HTMLDOM to add and delete related elements. For more information, see
JavaScript html dom elements (nodes)
Create a new HTML element
To add a new element to the html dom, you must first create the element (element node) and then append the element to an existing element.
Instance
This is a paragraph.
This is another paragraph.
《script》var para=document.createElement("p");var node=document.createTextNode("This is new.");para.appendChild(node);var element=document.getElementById("p1");element.appendChild(para);《script》
Example:
This code creates a new
Element:
var para=document.createElement("p");
To
You must first create a text node. This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must
Add the text node to the element:
para.appendChild(node);
Finally, you must append this new element to an existing element.
This code finds an existing element:
var element=document.getElementById("p1");
The following code adds a new element after an existing element:
element.appendChild(para);
Delete existing HTML elements
This code adds a new element to the existing element:
Instance
This is a paragraph.
This is another paragraph.
《script》var parent=document.getElementById("p1");var child=document.getElementById("p1");parent.removeChild(child);《script》
Instance resolution
This HTML document contains two subnodes (two
Element)
Element:
This is a paragraph.
This is another paragraph.
Find the element id = "p1:
var parent=document.getElementById("p1");
Find
Element:
var child=document.getElementById("p1");
Delete a child element from the parent element:
parent.removeChild(child);
Lamp can delete an element without referencing the parent element.
But unfortunately. DOM needs to understand the elements you want to delete and their parent elements.
This is a common solution: find the child element you want to delete and use its parentNode attribute to find the parent element:
var child=document.getElementById("p1");child.parentNode.removeChild(child);
JavaScript html dom-Change CSS
Html dom allows JavaScript to change the style of HTML elements.
Change HTML style
To change the style of HTML elements, use this syntax:
Document. getElementById (id). style. property = new style
The example below will change
Element style:
Instance
Hello World!
《script》document.getElementById("p2").style.color="blue";《script》The paragraph above was changed by a script.
In this example, the style of the HTML element id = "id1" is changed. when you click the button:
Instance
My Heading 1Click Me!