Skip to content
Related Articles

Related Articles

Improve Article

How to create an element from a string in JavaScript?

  • Last Updated : 07 Apr, 2021
Geek Week

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 two approaches as given below.

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.

Example: In this example, we create a heading element by specifying the string as “h2”.

HTML




<html>
<body>
  <h1 style="color:green">
    GeeksforGeeks
  </h1>
  
  <script>
    // Specify the string from which 
    // the elements would be created
    var str = "h2";
    var str2 = "p";
  
    // Creating the elements 
    var elem =
        document.createElement(str);
    var 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 jQuery parseHTML() method

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




<html>
<head>
  
  <!-- Include jQuery -->
  </script>
</head>
<body>
  <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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :