How to usethe createElement() method in Javascript

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">
        w3wiki
    </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:

How to create an element from a string in JavaScript ?

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:

Table of Content

  • Using the createElement() method
  • Using the DOMParser
  • Using the jQuery parseHTML() method
  • Using innerHTML

Similar Reads

Approach 1: Using the createElement() method

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....

Approach 2: Using the DOMParser

...

Approach 3: Using the jQuery parseHTML() method

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....

Approach 4: Using innerHTML

...