简体   繁体   English

如何包装element的所有子元素?

[英]How to wrapAll children of element?

I have : 我有 :

<div>
  <a> //this
    <span>sometext<span> //problem
  </a>
  <a></a> //this
  <a></a> //this
  <span>sometext</span> //this
  <div><div>
  <input>
</div>

I need to wrap marked elements and get result like this : 我需要包装标记的元素并获得如下结果:

<div>
  <div> //wrapped
    <a> 
      <span>sometext<span> 
    </a>
    <a></a> 
    <a></a> 
    <span>sometext</span>
  </div> //wrapped
    <div><div>
    <input>

</div>

But when i do this with $("div a, div span").wrapAll("<div></div>"); 但是当我用$("div a, div span").wrapAll("<div></div>"); its taking span from a but I didn't write div a span . 它的取值spana但我没有写div a span So I get this : 所以我得到这个:

<div>
  <div> //wrapped
    <a>       
    </a>
    <span>sometext<span> //need to be child of tag a
    <a></a> 
    <a></a> 
    <span>sometext</span>
  </div> //wrapped
    <div><div>
    <input>

</div>

You should do this by class: $(".classname").wrapAll(""); 您应该按类进行此操作: $(".classname").wrapAll(""); and add the class classname to your first div 并将类classname添加到您的第一个div

But it will be better to add a class/some other identifier to the container div 但是最好在容器div中添加一个类/其他标识符

<div class="someclass">
    <a> //this
        <span>sometext</span> //problem
    </a>
    <a></a> //this
    <a></a> //this
    <span>sometext</span> //this
    <div></div>
    <input />
</div>

then 然后

$("div.someclass").children("a, span").wrapAll("<div />");

Demo: Fiddle 演示: 小提琴

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

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