How to create an element from a string in JavaScript ?
Last Updated :
08 Jan, 2024
In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user.
This can be achieved using many approaches as given below:
The createElement() method is used for creating elements within the DOM. It accepts two parameters, a tagName which is a string that defines the type of element to create, and an optional options object that can be used to modify how the element is created. Any element that is needed can be passed as a string in this function and this would return the specified element. This approach can only be used to create a single element from one string.
Example: In this example, we create a heading element by specifying the string as "h2".
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Create an element from a string
</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<script>
// Specify the string from which
// the elements would be created
let str = "h2";
let str2 = "p";
// Creating the elements
let elem =
document.createElement(str);
let elem2 =
document.createElement(str2);
// Insert text in the element
elem.innerText =
"This is the new heading element";
elem2.innerText =
"This is the new paragraph element";
// Add the element to the body
document.body.appendChild(elem);
document.body.appendChild(elem2);
</script>
</body>
</html>
Output:

Approach 2: Using the DOMParser
The DOMParser is an API in JavaScript that allows you to parse HTML strings and create a DOM document from it. It provides a way to programmatically create and manipulate HTML documents in memory.
Example: In this example, we are using DOMParser
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Create an element from a string
</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<script>
// Create a string representing the element
const elementString = `<div id="myElement">This heading
is created by using DOMParser</div>`;
// Create a new DOMParser
const parser = new DOMParser();
// Parse the element string
const doc = ]
parser.parseFromString(elementString, 'text/html');
// Access the parsed element
const element = doc.body.firstChild;
// Now you can manipulate or append the element to the document
document.body.appendChild(element);
</script>
</body>
</html>
Output:
.png)
The parseHTML() method of jQuery is used to parse an HTML string so that it can be used to create elements according to the given HTML. This approach can be used to create multiple elements from the string.
Example: In this example, the string is specified with multiple elements that are parsed to HTML and added to the body of the document.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Create an element from a string
</title>
</head>
<body>
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.js">
</script>
<h1 style="color:green">
GeeksforGeeks
</h1>
<script>
// Define the HTML string to be parsed
str = "<p>This <i>element</i> is created by" +
" the <b>parseHTML()</b> " +
"method in <i>jQuery</i></p>";
// Parsing the string into HTML
html = $.parseHTML(str);
// Append the element in the document
$('body').append(html);
</script>
</body>
</html>
Output:

In this approach, we use the innerHTML
property to set the content of the existing container with the specified string, creating a new element inside it.
Example: In this example, we are using innerHTML.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Create Element Example</title>
</head>
<body>
<div id="yourContainerId"></div>
<script>
let container = document.getElementById("yourContainerId");
container.innerHTML =
"<div>Hello, I'm a new element!</div>";
</script>
</body>
</html>
Output:

Similar Reads
How to Get Character of Specific Position using JavaScript ? Get the Character of a Specific Position Using JavaScript We have different approaches, In this article we are going to learn how to Get the Character of a Specific Position using JavaScript Below are the methods to get the character at a specific position using JavaScript: Table of Content Method 1
4 min read
Remove a Character From String in JavaScript In JavaScript, a string is a group of characters. Strings are commonly used to store and manipulate text data in JavaScript programs, and removing certain characters is often needed for tasks like:Removing unwanted symbols or spaces.Keeping only the necessary characters.Formatting the text.Methods t
3 min read
Reverse a String in JavaScript We have given an input string and the task is to reverse the input string in JavaScript. Reverse a String in JavaScriptUsing split(), reverse() and join() MethodsThe split() method divides the string into an array of characters, reverse() reverses the array, and join() combines the reversed characte
1 min read
JavaScript - Convert String to Title Case Converting a string to title case means capitalizing the first letter of each word while keeping the remaining letters in lowercase. Here are different ways to convert string to title case in JavaScript.1. Using for LoopJavaScript for loop is used to iterate over the arguments of the function, and t
4 min read
JavaScript - Sort an Array of Strings Here are the various methods to sort an array of strings in JavaScript1. Using Array.sort() MethodThe sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values.JavaScriptlet a = ['Banana',
3 min read
How to Convert String to Camel Case in JavaScript? We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
4 min read
Extract a Number from a String using JavaScript We will extract the numbers if they exist in a given string. We will have a string and we need to print the numbers that are present in the given string in the console.Below are the methods to extract a number from string using JavaScript:Table of ContentUsing JavaScript match method with regExUsing
4 min read
JavaScript - Delete First Character of a String To delete the first character of a string in JavaScript, you can use several methods. Here are some of the most common onesUsing slice()The slice() method is frequently used to remove the first character by returning a new string from index 1 to the end.JavaScriptlet s1 = "GeeksforGeeks"; let s2 = s
1 min read
JavaScript - How to Get Character Array from String? Here are the various methods to get character array from a string in JavaScript.1. Using String split() MethodThe split() Method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument. JavaScriptlet s = "Geeksf
2 min read
JavaScript - How To Get The Last Caracter of a String? Here are the various approaches to get the last character of a String using JavaScript.1. Using charAt() Method (Most Common)The charAt() method retrieves the character at a specified index in a string. To get the last character, you pass the index str.length - 1.JavaScriptconst s = "JavaScript"; co
3 min read