JavaScript - innerHTML Property
The innerHTML property in JavaScript is used to get or set the HTML content inside an element. It is one of the most commonly used properties to manipulate content in web pages dynamically.
Syntax
element.innerHTML = "new content";
In the syntax above, element refers to the DOM element whose content you want to change, and new content is the HTML content you want to insert into the element.
Example of innerHTML Property
In this example, we change the content of a `<div>` element using the innerHTML property:
Example
<script type="text/javascript">
function changeContent() {
document.getElementById("demo").innerHTML = "Hello, this is the new content!";
}
</script>
<div id="demo">This is the original content.</div>
<input type="button" onclick="changeContent()" value="Change Content">
output
When the "Change Content" button is clicked, the content of the `
` element will change to "Hello, this is the new content!".
This is the original content.
Advanced Example: Adding HTML Elements with innerHTML
Example
<script type="text/javascript">
function addNewContent() {
var newContent = "<h2>New Section Added!</h2><p>This is a dynamically added paragraph.</p>";
document.getElementById("contentArea").innerHTML = newContent;
}
</script>
<div id="contentArea"><p>Original content before addition.</p></div>
<input type="button" onclick="addNewContent()" value="Add New Content">
output
When the "Add New Content" button is clicked, a new section with a heading and paragraph will be added to the page.
Original content before addition.