KAindex
KAindex

Reputation: 131

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!

Upvotes: 1

Views: 577

Answers (3)

Anthony McGrath
Anthony McGrath

Reputation: 802

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

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371019

Just use .appendChild?

const box1 = document.querySelector('.box-1');
const s1 = box1.parentElement;
box1.remove();
s1.appendChild(box1);
<div class="s1">
 <div class="box-1">b1</div>
 <div class="box-2">b2</div>
 <div class="box-3">b3</div>
 <div class="box-4">b4</div>
</div>

Upvotes: 0

qms
qms

Reputation: 142

To insert HTML without jQuery simply use insertAdjactedHTML function. https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Upvotes: 0

Related Questions