WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript HTML DOM - Changing HTML


The HTML DOM permits JavaScript to change the substance of HTML elements.


Changing the HTML Output Stream

JavaScript can make dynamic HTML content:

Date:

In JavaScript, document.write() can be utilized to compose specifically to the HTML yield stream:

Example

<!DOCTYPE html>
<html>
<body>

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

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

Changing HTML Content

The simplest approach to adjust the substance of a HTML component is by utilizing the innerHTML property.

To change the substance of a HTML component, utilize this syntax:

document.getElementById(id).innerHTML = new HTML

This precedent changes the substance 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 »

This model changes the substance of a <h1> element:

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

  • The HTML archive above contains a <h1> component with id="header"
  • We utilize the HTML DOM to get the component with id="header"
  • A JavaScript changes the substance (innerHTML) of that element

Changing the Value of an Attribute

To change the estimation of a HTML quality, utilize this sentence structure:

document.getElementById(id).attribute=new value

This model changes the estimation of the src trait of a <img> element:

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

  • The HTML archive above contains a <img> component with id="myImage"
  • We utilize the HTML DOM to get the component with id="myImage"
  • A JavaScript changes the src characteristic of that component from "smiley.gif" to "landscape.jpg"