In this tutorial, we will learn how to create an element from a string in JavaScript. Creating elements from a string in JavaScript is commonly used for scenarios where dynamic generation or manipulation of HTML content is required. This can be used when a user requires dynamic generation of the elements.
Elements can be created variously in Javascript :
Using the createElement() method :
We create JavaScript elements using the createElement() method. To create a particular element, we pass the item name as a string to the createElement() method.
A parameter the createElement(tagName) function contains is the name of the tag that will be generated through this method. Here, tagName is the name of the parameter and will be in the form of a string. Remember one string will generate just one element.
Syntax :
document.createElement("tagName")
In place of ‘tagName,’ there may be a paragraph, heading, image, etc. tags.
Through example it will be more clear to understand;
<html> <head> <title>Creating elements from string in JavaScriptnhi</title> </head> <body> <script> let string1="h2" let string2="p" let element1=document.createElement(string1) let element2=document.createElement(string2) element1.innerText="We are creating elements from string in javascript" element2.innerText="Creating element can be done by various approachs." document.body.append(element1) document.body.append(element2) </script> </body> </html>
Output for the above example:
We are creating elements from string in javascript
Creating element can be done by various approachs.
To run the element in the webpages we use DOM by appending. Here, the .append() or .appendChild() methods is used. Through the above example, it is clear how can we create elements from string using the createElement() method.
Using innerHTML method :
This sets or returns the HTML content of an element; in other words, it‘s the innerHTML property. The property allows manipulation of the inner content, including HTML tags, either by assigning new HTML strings or by retrieving existing content, making it a good candidate for dynamic updates on web pages.
Syntax :
object.innerHTML
It will be more clear through example,
<!DOCTYPE html> <html> <head> <title>HTML DOM innerHTML Property</title> </head> <body style="text-align: center"> <h1 style="color:green">Healthy Diet</h1> <h2>DOM innerHTML Property</h2> <p id="p">Eat healthy</p> <button onclick="eat()">Click me!</button> <script> function eat() { document.getElementById("p").innerHTML = "Stay healthy."; } </script> </body> </html>
Output:
Healthy Diet
Click Me!
Eat healthy
In the conclusion, we come to how we can create elements from string in javascript.