Files
30-seconds-of-code/snippets/createElement.md
Angelos Chalaris 611729214a Snippet format update
To match the starter (for the migration)
2019-08-13 10:29:12 +03:00

28 lines
696 B
Markdown

---
title: createElement
tags: browser,utility,beginner
---
Creates 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.
Set its `innerHTML` to the string supplied as the argument.
Use `ParentNode.firstElementChild` to return the element version of the string.
```js
const createElement = str => {
const el = document.createElement('div');
el.innerHTML = str;
return el.firstElementChild;
};
```
```js
const el = createElement(
`<div class="container">
<p>Hello!</p>
</div>`
);
console.log(el.className); // 'container'
```