bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/DOM and Browser APIs
JavaScript•DOM and Browser APIs

HTML DOM - Changing HTML

Changing HTML Content

The HTML DOM allows JavaScript to change both the text and the content of HTML elements.

The easiest way to modify the content is by using the innerHTML property:

document.getElementById( id ).
innerHTML = new HTML

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The innerHTML property is useful for getting or replacing the content of HTML elements.

The innerHTML property can be used to get or change any HTML element, including <html> and <body> .

Common Mistakes

  • Trying to access a DOM element before it exists
  • Forgetting the quotes in an id like "demo"
<p>

Example explained

  • The HTML document above contains a <p> element with id="p1"
  • We use the HTML DOM to get the element with id="p1"
  • A JavaScript changes the content ( innerHTML ) of that element to "New text!"
<h1>

Example explained

  • The HTML document above contains an <h1> element with id="id01"
  • We use the HTML DOM to get the element with id="id01"
  • A JavaScript changes the content ( innerHTML ) of that element to "New Heading"

Changing an Attribute

To change the value of an HTML attribute, use this syntax:

document.getElementById( id ).
attribute = new value
src

Example explained

  • The HTML document above contains an <img> element with id="myImage"
  • We use the HTML DOM to get the element with id="myImage"
  • A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"

Dynamic HTML content

Example

Formatted code
 <!DOCTYPE html>
<html>

<body>

<script>

document.getElementById("demo").innerHTML = "Date : " + Date();

</script>

</body>

</html>

Live preview

document.write()

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

Example

Formatted code
 <!DOCTYPE html>
<html>

<body>

<p>Bla bla bla</p>

<script>

document.write(Date());

</script>

<p>Bla bla bla</p>

</body>

</html>

Live preview

Warning !

Never use document.write() after the document is loaded. It will overwrite the document.

Previous

Selecting DOM Elements

Next

HTML DOM - Changing CSS

This chapter

Overview
16

Lessons

47m

Read time

1. The HTML DOM2. HTML DOM API3. Selecting DOM Elements4. HTML DOM - Changing HTML5. HTML DOM - Changing CSS6. HTML Form Validation7. HTML DOM Animation8. HTML DOM Document9. JavaScript Events10. JavaScript Mouse Events11. JavaScript Keyboard Events12. JavaScript Load Events13. JavaScript Timing Events14. JavaScript Event Management15. JavaScript HTML DOM Events16. JavaScript EventListener

On this page

Changing HTML ContentThe innerHTML PropertyCommon MistakesChanging an AttributeDynamic HTML contentdocument.write()Warning !