Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

DOM HTML

The HTML DOM enables JavaScript to modify the content of HTML elements.

Changing HTML Content

The simplest way to modify the content of an HTML element is by using the innerHTML property.

To update the content of an HTML element, use the following syntax:

document.getElementById(id).innerHTML = new HTML

This example updates the content of a <p> element:

Example

<html>
<body>

<p id=”p1″>Hello World!</p>

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

</body>
</html>

Explanation of the example:

  • The HTML document contains a <p> element with id=”p1″.
  • We use the HTML DOM to access the element with id=”p1″.
  • A JavaScript function changes the content (innerHTML) of that element to “New text!”.

This example updates the content of an <h1> element:

Example

<!DOCTYPE html>
<html>
<body>

<h1 id=”id01″>Old Heading</h1>

<script>
const element = document.getElementById(“id01”);
element.innerHTML = “New Heading”;
</script>

</body>
</html>

Explanation of the example:

  • The HTML document contains an <h1> element with id=”id01″.
  • We use the HTML DOM to access the element with id=”id01″.
  • JavaScript changes the content (innerHTML) of that element to “New Heading”.