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 can be used along with getElementById()
within your JavaScript code to refer to an HTML element and change its contents.
The innerHTML
Syntax
You can use innerHTML
to set content like this:
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 = 'Hey <strong>Thanks!</strong>';
is setting the inner HTML of the myText element to Hey Thanks!.
Example of 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.
User Input with textContent
In a case like the previous example, we probably don't want the user to enter any HTML. We just want them to enter their name in plain text. When outputting plain text without HTML tags, it's usually more appropriate to use textContent
rather than innerHTML
.
So if we replace innerHTML
with textContent
it would look like this:
Formatting with getElementById()
innerHTML
and textContent
are just two of many properties we can use to manipulate the DOM.
In this example, we use getElementById()
to to detect the color that the user has selected. We then use it again, in conjunction with style.background
to apply the new color. In both cases, we refer to the HTML elements by their ID (using getElementById()
.)