Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move div content into another div using pure javascript

Tags:

javascript

I have this HTML setup:

<div class="one">
    <div class="text">One</div>
    <div class="text">One</div>
</div>

<div class="two">
    <div class="text">Two</div>
    <div class="text">Two</div>
</div>

I want to move the content of div .two into .one using pure javascript (not jQuery) so we get:

<div class="one">
    <div class="text">One</div>
    <div class="text">One</div>
    <div class="text">Two</div>
    <div class="text">Two</div>
</div>

What is the best way to do this with millisecond performance in mind?

like image 733
Henrik Petterson Avatar asked Dec 14 '22 19:12

Henrik Petterson


1 Answers

I personally prefer insertAdjacentElement as it gives you more control as to where to put elements, but be careful to take note of its browser support.

const one = document.querySelector('.one');
const two = document.querySelector('.two');

[...two.children].forEach(element => {
  one.insertAdjacentElement('beforeEnd', element);
});
<div class="one">
    <div class="text">One</div>
    <div class="text">One</div>
</div>

<div class="two">
    <div class="text">Two</div>
    <div class="text">Two</div>
</div>

Also note that I've used ES2015 syntax.

like image 95
evolutionxbox Avatar answered Dec 16 '22 10:12

evolutionxbox