This tutorial will describe the methods to write HTML code dynamically using JavaScript.
How to Write HTML Code Dynamically Using JavaScript?
To write HTML code using JavaScript, use the following methods:
Method 1: Write HTML Code Dynamically Using document.createElement() Method
JavaScript’s “document.createElement()” method with the “textContent” property is used to write an HTML code in JavaScript dynamically. Using the createElement() method, you can create a certain HTML element, and the textContent property is used to set the text content.
Syntax
Use the given syntax to create an HTML element in JavaScript:
Example
Here, first, we will create a paragraph in a JavaScript file using the HTML <p> tag passed in a “createElement()” method:
Use the textContent property to set the text in a paragraph:
Finally, print the text on the webpage using the “document.write()” method:
Here, you can see in the output we successfully write the text on the web page using JavaScript:
Method 2: Write HTML Code Dynamically Using innerHTML Property
To write HTML code dynamically, use the JavaScript “innerHTML” property. It is the simplest approach to change the content of an HTML element. It supports all browsers.
Syntax
Follow the given syntax to use the innerHTML property:
Example
In the HTML file, first, create a button that will call the defined function “heading()” in JavaScript on the click event:
Create a paragraph using <p> tag where the text will be shown from the JavaScript and assign an id to it:
Define a function “heading()” in a JavaScript file. Get the reference of the HTML element using its assigned id with the help of the “getElementById()” method and apply an “innerHTML” property on it:
document.getElementById('heading').innerHTML="<h1>Welcome To Linuxhint</h1>";
}
Output
We have compiled all the essential information related to writing the HTML code dynamically using JavaScript.
Conclusion
To write HTML code dynamically in JavaScript, use the “document.createElement()” method with the “textContent” property or the “innerHTML” property. In the first method, you don’t need any HTML code, while in the innerHTML property, you need to access the HTML element and perform an operation on it. In this tutorial, we described the methods to write HTML code using JavaScript dynamically.