The innerHTML
property in JavaScript allows you to get or set the HTML content of an element as a string.
Syntax For
Getting HTML content of an element:
let element = document.getElementById("myElementId");
let htmlContent = element.innerHTML;
Setting HTML content of an element:
let element = document.getElementById("myElementId");
element.innerHTML = "New HTML content";
Here are step-by-step instructions on how to use the innerHTML
property in JavaScript
Step 1: Access an HTML element
Use JavaScript to select the HTML element you want to manipulate. You can do this using various methods like document.getElementById()
, document.querySelector()
, or document.querySelectorAll()
.
<div id="myElement">Initial content</div>
let element = document.getElementById("myElement");
Step 2: Get the HTML content
If you want to retrieve the current HTML content of the element, use the innerHTML
property.
let htmlContent = element.innerHTML; console.log(htmlContent);
// Output: Initial content
Step 3: Set the HTML content
If you want to replace or update the HTML content of the element, assign a new HTML string to the innerHTML
property.
element.innerHTML = "<b>New content</b>";
Step 4: Verify the changes(optional)
You can optionally verify that the HTML content has been updated as expected by accessing the element again or using browser developer tools.
console.log(element.innerHTML);
// Output: <b>New content</b>
Example: Here, we have show the code on how to use innerHTML in JavaScript.
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content=" width = device -width,
initial-scale = 1 .0">
< title >innerHTML Example</ title >
< style >
.container {
padding: 10px;
}
</ style >
</ head >
< body >
< div class = "container" id = "myElement" >Initial content</ div >
< button onclick = "changeContent()" >Change Content</ button >
< script >
function changeContent() {
let element = document.getElementById("myElement");
element.innerHTML = "< b >New content</ b >";
}
</ script >
</ body >
</ html >
|
Output: