Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make mutliple times of insertAdjacentElement

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading