HTML DOM Modification
Modify HTML = change elements, attributes, styles and events.
Modify HTML Elements
Modifying the HTML DOM means many different things:
Change HTML content
Change CSS styles
Change HTML attributes
Create new HTML element
Remove existing HTML elements
change event (handler)
In the next chapters, we'll dive into common ways to modify the HTML DOM.
Create HTML Content
The easiest way to change the content of an element is to use the innerHTML attribute.
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> paragraphs are scripted to modify the content. </p>
![]() | We will explain to you the details of the example in the following sections. |
---|
Change HTML Style
The HTML DOM gives you access to HTML elements' style objects.
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 Element
To add a new element to the HTML DOM, you must first create the element (an 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>