Skip to content

JavaScript create element from string

  • by

In JavaScript, you can create an element from a string using the createElement method of the document object. This approach can be useful when you need to create elements dynamically based on user input or other variables.

To create an element from a string in JavaScript, you can use the following syntax:

const elementString = "<elementName>Element content</elementName>";
const element = document.createElement("elementName");
element.innerHTML = elementString;

However, for more complex web applications, it’s generally recommended to use templating libraries or frameworks, such as React or Angular.

JavaScript creates an element from a string example

A simple example code creates a div element with some content using a string in JavaScript, and then add it to the DOM:

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Create Element From String</title>
  </head>
  <body>
    <div id="parent"></div>
    <script>
      // Create the div element from a string
      const divString = "<div>This is some content inside a div element</div>";
      const divElement = document.createElement("div");
      divElement.innerHTML = divString;

      // Add the div element to the DOM
      const parentElement = document.querySelector("#parent");
      parentElement.appendChild(divElement);
    </script>
  </body>
</html>

Output:

JavaScript create element from string

Function to create an element from an HTML string in JavaScript.

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}
  1. Create a new div element using the createElement method.
  2. Set the innerHTML property of the div element to the HTML string passed as an argument, using the trim method to remove any leading or trailing whitespace.
  3. Return the firstChild of the div element, which represents the first child node of the div element.

Here’s an example of how you could use this function to create a div element with some content:

const htmlString = "<div>This is some content inside a div element</div>";
const divElement = createElementFromHTML(htmlString);
document.body.appendChild(divElement);

Comment if you have any doubts or suggestions on this JS basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading