WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript HTML DOM - Changing HTML


The HTML DOM allows JavaScript to alter the content of HTML elements.


Changing the HTML Output Stream

JavaScript can create dynamic HTML content:

Today's date is: Sat Dec 21 2019 16:14:50 GMT + 0530 (India Standard Time)

In JavaScript, document.write () can be used to write content directly to the HTML output stream.

Example

<!DOCTYPE html>
<html>
<body>

<script>
document.write(Date());
</script>

</body>
</html>
Try it yourself »

Changing HTML Content

The easiest way to modify HTML content is to use the innerHTML attribute.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML

This example changed <p> Element content:

Example

<html>
<body>

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

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

</body>
</html>
Try it Yourself »

This example changed <h1> Element content´╝Ü

Example

<!DOCTYPE html>
<html>
<body>

<h1 id="header">Old Header</h1>

<script>
var component = document.getElementById("header");
element.innerHTML = "New Header";
</script>

</body>
</html>
Try it Yourself »

Example explanation:

  • The above HTML document contains id = "header" <h1> Element

  • We use HTML DOM to get the element with id = "header"

  • JavaScript changes the content of this element (innerHTML)


Change HTML attributes

To change the attributes of an HTML element, use this syntax:

document.getElementById(id).attribute=new value

This example changes <img> Element's src attribute:

Example

<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>
Try it Yourself »

Example explanation:

  • The above HTML document contains id = "image" <img> Element
  • We use HTML DOM to get the element with id = "image"
  • JavaScript changes the attributes of this element (change "smiley.gif" to "landscape.jpg")