简体   繁体   English

Javascript包装元素并插入相同的位置

[英]Javascript wrap element and insert at 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> 

Now I would like to insert the this.newWrap at the same position the element it wraps is. 现在我想将this.newWrap插入它所包含的元素的相同位置。 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() 所以说使用相同的选择器我用来包装元素在这种情况下document.querySelector('.two')而不是document.querySelector('.three')就像在.insertBefore()看到的那样

How can I do that? 我怎样才能做到这一点?

Now I would like to insert the this.newWrap with the same selector I use to wrap the element... 现在我想插入this.newWrap与我用来包装元素的相同选择器...

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: 如果你的意思是同一个父母 ,并且在那个父母的子列表中的同一个地方,你确实使用了insertBefore - 在移动你要包装的元素之前:

 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. 即使在其父元素的最后一个元素上也是如此,因为在这种情况下, nextSibling将为null ,如果将null作为“before”元素传递给insertBefore ,则它会追加到末尾。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM