Javascript wrapper element and insert in same position

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>
Run codeHide result

Now I would like to insert this.newWrapin the same position as the element that it wraps. So to speak using the same selector that I use to wrap the element in this case document.querySelector('.two'), and not document.querySelector('.three'), as shown in.insertBefore()

How can i do this?

+4
source share
1 answer

Now I would like to insert this.newWrapwith the same selector that I use to wrap the element ...

If you mean the same parent and in the same place on this parent child list, you really use insertBefore- before moving the item you are 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>
Run codeHide result

, — :

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>
Hide result

, nextSibling null, null "before" insertBefore, ,: -)

+2

Source: https://habr.com/ru/post/1679606/


All Articles