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
  • Delete Existing HTML Elements
  • Change Events (Handlers)

In the following chapters, we will learn common methods for modifying the HTML DOM in depth.


Create HTML Content

The simplest way to change element content is to use 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 paragraph content is modified by a script.</p>

Try it yourself »

lamp 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 yourself »


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 yourself »
Other Extensions