1

I want to supply options of the function. Syntax is(https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement):

let element = document.createElement(tagName[, options]);

There are several related questions, but most answers recomends to create element, and then use element.addClass, for instance, or to create an independent Js function to achieve this. If there is a way to do it in a single line, providing array of options, how is it? Can you provide an example? Answer to this, will also help these: assigning DOM attributes with javascript's createElement function How can I add a class to a DOM element in JavaScript?

Laynier Piedra
  • 425
  • 6
  • 16
  • 1
    From that linked page: "An optional `ElementCreationOptions` object, containing a single property named `is`, whose value is the tag name of a custom element previously defined via `customElements.define()`. " So, that's for custom elements. – Heretic Monkey Jul 09 '21 at 14:16

1 Answers1

3

The second parameter accepts an ElementCreationOptions object which contains a single property.

Instead, if you want to add properties in one line, you have to use Object.assign().

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.MDN

const elem = Object.assign(document.createElement("h1"), {className:"red", textContent:"red"});
document.body.appendChild(elem);
.red{
  color:red;
}
Spectric
  • 30,714
  • 6
  • 20
  • 43