Search w3schools.com:

SHARE THIS PAGE

HTML DOM - Modifying


Modifying HTML = Changing Elements, Attributes, Styles, and Events.


Modifying HTML Elements

Modifying the HTML DOM can be many different things

  • Changing HTML content
  • Changing CSS styles
  • Changing HTML attributes
  • Creating new HTML elements
  • Removing existent HTML elements
  • Changing event(handlers)

In the next chapters we will take a closer look at the most common ways to modify the HTML DOM.


Changing HTML Content

The easiest 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

<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML="New text!";
</script>

</body>
</html>

Try it yourself »

lamp The examples are explained in details in the next chapters.


Changing HTML Style

With the HTML DOM you can access the style object of HTML elements.

The following example changes the HTML style of a paragraph:

Example

<html>

<body>

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

<script>
document.getElementById("p2").style.color="blue";
</script>

</body>
</html>


Try it yourself »


Creating New HTML Elements

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

 Example

<div id="d1">
<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 new.");
para.appendChild(node);

var element=document.getElementById("d1");
element.appendChild(para);
</script>

Try it yourself »



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]