HTML DOM modification
Modify HTML = change elements, attributes, styles and events.
Edit HTML elements
Modify HTML DOM means many different aspects:
- Change the HTML content
- Change CSS Styles
- Change the HTML attributes
- Create a new HTML element
- Remove the existing HTML elements
- Change event (handler)
In the following sections, we will study in depth the HTML DOM to modify the conventional method.
Create HTML content
The easiest way to change the content of the element is to use the innerHTML property.
The following example changes the contents of a HTML <p> element:
Examples
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
try it"
We will explain to you the details of the example in the following sections. |
Change HTML styles
Through the HTML DOM, you can access the object style HTML elements.
The following example to change a HTML paragraph style:
Examples
<html>
<body>
<body>
<p id="p2">Hello world!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
</body>
</html>
try it"
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 it to the existing elements.
Examples
<div id="d1">
<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("d1");
element.appendChild(para);
</script>
<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("d1");
element.appendChild(para);
</script>
try it"