Detailed description of how JavaScript operates HTML elements and styles, and detailed description of javascript
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
<div id="div1"><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 new.");para.appendChild(node);var element=document.getElementById("div1");element.appendChild(para);</script>
Example:
This Code creates a new <p> element:
var para=document.createElement("p");
To add text to the <p> element, 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 append the text node to the <p> 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("div1");
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
<div id="div1"><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>
Instance resolution
This HTML document contains <div> elements with two subnodes (two <p> elements:
<div id="div1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div>
Find the element id = "div1:
var parent=document.getElementById("div1");
Find the <p> element of id = "p1:
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 following example changes the <p> element style:
Instance
In this example, the style of the HTML element id = "id1" is changed. When you click the button:
Instance
<!DOCTYPE html>