Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML
IMCreator - Free Website Builder

InnerHTML In JavaScript

The innerHTML property can be used to modify your document's HTML on the fly.

When you use innerHTML, you can change the page's content without refreshing the page. This can make your website feel quicker and more responsive to user input.

The innerHTML property is used along with getElementById within your JavaScript code to refer to an HTML element and change its contents.

The innerHTML property is not actually part of the official DOM specification. Despite this, it is supported in all major browsers, and has had widespread use across the web for many years. DOM, which stands for Document Object Model, is the hierarchy that you can use to access and manipulate HTML objects from within your JavaScript.

The innerHTML Syntax

The syntax for using innerHTML goes like this:

Code

In this syntax example, {ID of element} is the ID of an HTML element and {content} is the new content to go into the element.

Basic innerHTML Example

Here's a basic example to demonstrate how innerHTML works.

This code includes two functions and two buttons. Each function displays a different message and each button triggers a different function.

In the functions, the getElementById refers to the HTML element by using its ID. We give the HTML element an ID of "myText" using id="myText".

So in the first function for example, you can see that document.getElementById('myText').innerHTML = 'Thanks!'; is setting the innerHTML of the "myText" element to "Thanks!".

CodeResult

Example 2: innerHTML With User Input

Here's an example of using innerHTML with a text field. Here, we display whatever the user has entered into the input field.

CodeResult

Example 3: Formatting with getElementById

In this example, we use the getElementById property to detect the color that the user has selected. We can then use style.background to apply the new color. In both cases, we refer to the HTML elements by their ID (using getElementById.)

CodeResult

Choose a background color...

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!