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:


<p id="p1">Hello World!</p>
document.getElementById("p1").innerHTML="New text!";
<p> paragraphs are scripted to modify the content. </p>

Try It! 

lampWe 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:


<p id="p1">Hello world!</p>
<p id="p2">Hello world!</p>

Try It! 

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.


<div id="div1">
    <p id="p1" > this is a paragraph. </p>
    <p id="p2" > this is another paragraph. </p>

    var para=document.createElement("p");
    var node=document.createTextNode ("This is a new paragraph.") );
    var element=document.getElementById("div1");