How do I make multiple times of insertAdjacentElement like below?
test.insertAdjacentElement('afterend',elm1);
test.insertAdjacentElement('afterend',elm2);
test.insertAdjacentElement('afterend',elm3);
I can make a function to refactor it, but is there any shortcut to doing this? Like:
test.insertAdjacentElement('afterend',elm1, elm2, elm3);
>Solution :
If you’re inserting at the end of a container, you can use append, which accepts multiple arguments.
containerOfTest.append(elm1, elm2, elm3)
Otherwise, a very simple loop would do.
for (const elm of [elm1, elm2, elm3]) {
test.insertAdjacentElement('afterend',elm);
}
Another option is to create a DocumentFragment, insert all elements into it, and then insert the fragment (only once) into the DOM.
const test = document.querySelector('.test');
const elm1 = document.createElement('div');
const elm2 = document.createElement('div');
const elm3 = document.createElement('div');
const fragment = new DocumentFragment();
fragment.append(elm1, elm2, elm3);
test.parentElement.insertBefore(fragment, test.nextElementSibling);
console.log(document.body.innerHTML);
<div class="test">test</div>