Search code examples
javascripthtmlcsschild-nodesparent-node

Insert div as the .lastElementChild without 'insertBefore' without jQuery


Okay so I've usually had .box-4 as the last element inside of .s1 as shown below:

<div class="s1">
 <div class="box-1"></div>
 <div class="box-2"></div>
 <div class="box-3"></div>
 <div class="box-4"></div>
</div>

and had .box-1 move before .box-4 using the JavaScript:

var box1 = document.querySelector('.box-1');
var s1 = box1.parentNode;

s1.insertBefore(box1, s1.lastElementChild);

to receive the following outcome:

<div class="s1">
 <div class="box-2"></div>
 <div class="box-3"></div>
 <div class="box-1"></div>
 <div class="box-4"></div>
</div>

however, I have recently removed .box-4 from .s1, and consequently .box-1 no longer move/becomes the .lastElementChild. I would still like .box-1 to move, and hence become last, however, I'm unsure of what command will achieve this; desirably something like this

.insertAs(box1, s1.lastElementChild);

to achieve this:

<div class="s1">
 <div class="box-2"></div>
 <div class="box-3"></div>
 <div class="box-1"></div>
</div>

NOTE: .box-1 changes position depending on screen-width, so simply moving the div in HTML is not an option.

NOTE: Vanilla JavaScript only - No jQquery.

Thanks in advance guys, much appreciated!


Solution

  • Below will append box1 as the last child (automatically removes it from it's original position).

    var box1 = document.querySelector('.box-1');
    var s1 = box1.parentNode;
    
    s1.appendChild(box1);