Use ParentNode.append()
we can do stuff like i.e: myNav.append(EL_logo, EL_list, EL_btn).
Here's a concept I like really much by using a reusable Element constructor:
/**
* Create new Element helper
* @param {String} tag Element TagName selector
* @param {Object} attr Element attributes
*/
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
Append Elements to DOM
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
const EL_h1 = EL("h1", {
textContent: "Hello, World!"
});
const EL_btn = EL("button", {
textContent: "Click me!",
type: "button",
style: "color: blue;",
onclick() {
alert(this.textContent);
}
});
document.body.append(EL_h1, EL_btn);
Grouping using DocumentFragment
and appending DocumentFragment
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
const EL_a = EL("div", {
textContent: "Some DIV Lorem ipsum"
});
const EL_b = EL("div", {
innerHTML: "dolor <b>sit amet</b>"
});
const DF = new DocumentFragment();
DF.append(EL_a, EL_b); // Append to DocumentFragment first
// Here you can still manipulate DF using i.e: DF.querySelectorAll('div');
document.body.append(DF); // Append DocumentFragment
Elements from Array
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
// Prepare UL Element
const EL_ul = EL('ul');
// Function for LI Element
const EL_Li = (textContent) => EL('li', {
textContent,
onclick( evt ) {
console.log(this.textContent);
}
});
const DF_list = new DocumentFragment();
const items = ["Click me!", "Lorem", "Ipsum", "Dolor"];
items.forEach(item => DF_list.append(EL_Li(item)));
EL_ul.append(DF_list);
// Finally append the UL element somewhere
document.body.append(EL_ul);
document.appendChild(div), try usedocument.documentElement.appendChild(div)