简体   繁体   中英

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>"); its taking span from a but I didn't write 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(""); and add the class classname to your first div

But it will be better to add a class/some other identifier to the container 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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