HTML DOM - Modifying
Modifying HTML = changing elements, attributes, styles, and events.
Modify HTML Elements
Modifying the HTML DOM means many different aspects:
- Change HTML Content
- Change CSS Style
- Change HTML Attributes
- Create New HTML Elements
- Remove an Existing HTML Element
- Change Events (Handlers)
In the following chapters, we will learn in depth the common methods for modifying the HTML DOM.
Create HTML Content
The easiest way to change the content of an element is to use the innerHTML property.
The following example changes a
element's HTML content:
Example
<p id="p1">Hello World!
p
<
script
document.getElementById("p1").innerHTML="new text!";
script
<
p
The paragraph content is modified by a script.
p
Try it »
![]() |
We will explain the details of the example in the following chapters. |
|---|
Change HTML Style
Through the HTML DOM, you can access the style object of HTML elements.
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
Try it »
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
Try it »
