Files
30-seconds-of-code/snippets/createElement.md
Isabelle Viktoria Maciohsek 5e8e6f51a3 Update snippet descriptions
2020-10-19 18:51:03 +03:00

29 lines
719 B
Markdown

---
title: createElement
tags: browser,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.
- 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.
```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'
```