JavaScript: Create an element from a string

JavaScript fundamental (ES6 Syntax): Exercise-250 with Solution

Write a JavaScript program to create an element from a string (without appending it to the document).

If the given string contains multiple elements, only the first one will be returned.

  • Use Document.createElement() to create a new element.
  • Use Element.innerHTML to set its inner HTML to the string supplied as the argument.
  • Use ParentNode.firstElementChild to return the element version of the string.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const createElement = str => {
  const el = document.createElement('div');
  el.innerHTML = str;
  return el.firstElementChild;

const el = createElement(
  `<div class="container">
console.log(el.className); // 'container'

Sample Output:



flowchart: Create an element from a string.

Live Demo:

See the Pen javascript-basic-exercise-250-1 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get the current URL.
Next: Write a JavaScript program to write a JSON object to a file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.