The innerHTML property is used to set or retrieve the inner HTML of the element between the start and end tags of the object. Each HTML element has innerHTML property which defines both code and text between start and end tag. In most of the cases, we use this property inside a “div” tag to insert HTML snippet dynamically. This is very useful when we want to change the content of the display component at run time.
The elements which do not have both start and end tag cannot have an innerHTML property. It takes combination of text and elements. When the innerHTML property is set, the given string is replaces the existing content of the object. The innerHTML property is valid for only block and inline elements.
Inner HTML Syntax
HTMLElementObject.innerHTML=text
Example Using innerHTML Property
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>innerHTML property</title> <script> function changeText() { document.getElementById("myform").innerHTML = "Mahantesh"; } </script> </head> <body> <p> Welcome User: <b id="myform">Ganesh</b> </p> <input type="button" onclick="changeText()" value="Change Text" /> </body> </html>
- document.getElementById(“myform”).innerHTML = “Mahantesh”; line indicates that it will change the text as Mahantesh with existing text Ganesh by using getElementById method.
- Welcome User: Ganesh line determines that the id name “myform” will be using in function changeText() to replace with new text value.
- <input type=”button” onclick=”changeText()” value=”Change Text” /> tag uses onclick attribute which triggers when user clicks the mouse button once.
Inner HTML Demo
- Save the file as innerhtml_property.html in your system.
- Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML specification.