HTML DOM - Modify
Modify HTML = Change elements, attributes, styles, and events.
Modify HTML Elements
Modifying the HTML DOM means many different aspects:
- Change HTML content
- Change CSS styles
- Change HTML attributes
- Create new HTML elements
- Remove existing HTML elements
- Change events (handlers)
In the following sections, we will delve into the common methods for modifying the HTML DOM.
Create HTML Content
The simplest way to change the content of an element is by using the innerHTML property.
The following example changes the HTML content of a <p> element:
Example
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
<p>The content of the paragraph is changed by script.</p>
| | We will explain the details in the examples in the following sections. | | --- | --- |
Change HTML Styles
Through the HTML DOM, you can access the style object of an HTML element.
The following example changes the HTML style of a paragraph:
Example
<p id="p1">Hello world!</p>
<p id="p2">Hello world!</p>
<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial";
document.getElementById("p2").style.fontSize="larger";
</script>
Create New HTML Elements
To add a new element to the HTML DOM, you must first create the element (element node) and then append it to an existing element.
Example
<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 a new paragraph.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>