w3resource

JavaScript: Create an element from a string

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

Create Element from String

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 
// Define a function 'createElement' that creates a DOM element from the provided HTML string
const createElement = str => {
  // Create a new div element
  const el = document.createElement('div');
  // Set the innerHTML of the div to the provided HTML string
  el.innerHTML = str;
  // Return the first element child of the div
  return el.firstElementChild;
};

// Call 'createElement' with a sample HTML string and assign the result to 'el'
const el = createElement(
  `<div class="container">
    <p>Hello!</p>
  </div>`
);

// Log the className property of the created element 'el'
console.log(el.className); // 'container'

Output:

container

Flowchart:

flowchart: Create an element from a string.

Live Demo:

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


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that creates a DOM element from an HTML string without appending it to the document.
  • Write a JavaScript function that parses a string of HTML and returns the first element node found.
  • Write a JavaScript program that converts a string to a DocumentFragment and extracts its child nodes.
  • Write a JavaScript function that safely creates an element from a string and sets its innerHTML, then returns the element.

Go to:


PREV : Get Current URL.
NEXT : Write JSON to File.

Improve this sample solution and post your code through Disqus

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.