Element
The element
utility exists solely to help you create DOM elements easily.
It takes two arguments and only the first one is required.
element(TAG_NAME, OPTIONS)
- TAG_NAME: The name of the tag you want to create. It can be native tag names or custom web components.
-
OPTIONS (optional):
- attributes: an object keyed by attribute name and value can be any valid value. It also supports inline event listeners.
- htmlContent: an HTML string to be parsed as content.
- textContent: a text to be used as plain text content.
- ns: the namespace URI of the element.
Why use this
Creating DOM element the native way is a multiline experience, especially with events or if you want to handle web components.
const button = document.createElement('button');
button.type = "button";
button.disabled = true;
button.textContent = "click me";
button.onclick = () => {
// handle click
}
With element
it looks like this:
const button = element('button', {
textContent: 'click me',
attributes: {
type: 'button',
disabled: true,
onclick: () => {
// handle click
}
}
})
Doing it all in one call is not the only reason. There are other advantages:
- Event listener: It will convert inline event handlers to event listeners for you. Which means the event attribute will not be placed on the element.
- Web component properties: If you create a web component instance that maps attributes to internal setters it will automatically provide them as properties as well.