Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript wrap element and insert at same position

Tags:

javascript

I have the following code

this.newWrap = document.createElement("div");
this.newWrap.classList.add('xxx');

this.newWrap.appendChild(
    document.querySelector('.two')
);

document.querySelector('.wrap').insertBefore(
    this.newWrap,
    document.querySelector('.three')
);
.xxx {
  background-color: orange;
}
<div class="wrap">
    <div class="one">One</div>
    <div class="two">two</div>
    <div class="three">three</div>
    <div class="four">four</div>
    <div class="five">five</div>
</div>

Now I would like to insert the this.newWrap at the same position the element it wraps is. So to say with the same selector I use to wrap the element in this case document.querySelector('.two') and not document.querySelector('.three') like seen in the .insertBefore()

How can I do that?

like image 439
caramba Avatar asked Oct 18 '22 10:10

caramba


1 Answers

Now I would like to insert the this.newWrap with the same selector I use to wrap the element...

If you mean the same parent, and in the same place in that parent's child list, you do indeed use insertBefore — before moving the element you're wrapping:

this.newWrap = document.createElement("div");
this.newWrap.classList.add('xxx');
var toWrap = document.querySelector('.two');
toWrap.parentNode.insertBefore(this.newWrap, toWrap);
this.newWrap.appendChild(toWrap);
.xxx {
  background-color: orange;
}
<div class="wrap">
    <div class="one">One</div>
    <div class="two">two</div>
    <div class="three">three</div>
    <div class="four">four</div>
    <div class="five">five</div>
</div>

If you prefer to move the element first, though, that is also an option — you just keep track of its former parent and following sibling:

this.newWrap = document.createElement("div");
this.newWrap.classList.add('xxx');
var toWrap = document.querySelector('.two');
var parent = toWrap.parentNode;
var next = toWrap.nextSibling;
this.newWrap.appendChild(toWrap);
parent.insertBefore(this.newWrap, next);
.xxx {
  background-color: orange;
}
<div class="wrap">
    <div class="one">One</div>
    <div class="two">two</div>
    <div class="three">three</div>
    <div class="four">four</div>
    <div class="five">five</div>
</div>

That works even on the last element in its parent, because in that case nextSibling will be null, and if you pass null as the "before" element to insertBefore, it appends to the end. :-)

like image 131
T.J. Crowder Avatar answered Oct 21 '22 03:10

T.J. Crowder