- This property is used to set or return the HTML content inside an element.
- Using innerHTML, you can change HTML content inside element tags as you like, but not the tags themselves.
innerHTML Property Explained
So, what is innerHTML? Let's start by reminding everyone that every HTML element has an inner HTML property. It is used to define HTML tags and also the content that is inserted between them. This property is one of the components of the DOM that lets developers manipulate the appearances of web pages. In other words, it allows you to get information about all DOM elements.
This property is used to set or return the HTML content inside an element:
document.getElementById("samplePara").innerHTML = "Help! This paragraph has changed!";
To return the HTML content inside an element, you should follow this code example:
HTMLElementObject.innerHTML = text
Text specifies the HTML content inside an element. As a parameter, it is used to make modifications to the text of the element. After applying it, you will be able to change texts that are positioned between different HTML tags.
There are no limitations to the type of tags the inner HTML can set and return. Therefore, feel free to practice. The more you try, the more you learn!
To help you understand what is innerHTML property and how it's used, we'll provide you with useful code examples that you can practice your code-writing skills on. After you click the Try it Live button, you will be able to make modifications and learn without having to leave the browser!
The first example displays how you can make modifications to two DOM elements:
document.getElementById("samplePara").innerHTML = "Hello, sir, what seems to be the problem?"; document.getElementById("sampleDiv").innerHTML = "It's the paragraph. It changed!";
The following code is used to alert the content of
You can also remove the HTML content from the
<p> tag with the following code:
document.getElementById("samplePara").innerHTML = "";
The final code example shows the code for when you want to modify the content of HTML element, its URL, and the target of a link:
document.getElementById("sampleAnchor").innerHTML = "BitDegree"; document.getElementById("sampleAnchor").href = "https://www.BitDegree.org"; document.getElementById("sampleAnchor").target = "_blank";