HTML code dynamically using JavaScript

The most straightforward approach to altering the content of an HTML element involves using the innerHTML property. This property facilitates the retrieval or assignment of HTML or XML markup that resides within the given element. With widespread support across contemporary web browsers, this property empowers us to seamlessly assign fresh HTML or textual content to any container element. Subsequently, the page undergoes immediate updates and reflows to seamlessly present the updated content, thereby ensuring a streamlined user experience.

document.getElementById('test').innerHTML="<h2>This is heading using JavaScript</h2>";
run this source code Browser View
This will change...

Source
<html> <body> <div id="test"><b>This will change...</b></div> <button onclick="changeIt()">Change....</button> <script> function changeIt() { document.getElementById('test').innerHTML="<h2>Changed using innerHTML!!</h2>"; } </script> </body> </html>
Example explained:

In the above HTML document, there exists a < div > element identified by the id="test". To manipulate this element using the HTML Document Object Model (DOM), JavaScript can be employed to access the element with the specified identifier. Subsequently, through the utilization of the innerHTML property, the content of the identified element can be dynamically altered to read "Changed using innerHTML!!". This approach seamlessly facilitates the modification of the HTML content within the designated < div > element.

innerHTML

The term "innerHTML" refers to a DOMString encompassing the HTML representation of the element's nested elements. When the value of innerHTML is modified, it effectively eliminates all existing descendants of the element and subsequently substitutes them with nodes formed by interpreting the HTML provided within the specified "htmlString". This property finds frequent application within web pages, particularly in generating dynamic HTML components like registration forms, comment sections, and hyperlinks, thereby contributing to the dynamic interactivity and content presentation of websites.

Conclusion

JavaScript enables the dynamic manipulation of HTML code by using properties like "innerHTML". This mechanism allows developers to modify and generate HTML content on the fly, facilitating dynamic interactions and content updates within web applications. This approach is commonly used for tasks like creating forms, comments, and links dynamically in response to user interactions.