开发者

need to wrap h3 and div in wrapper div with jquery

开发者 https://www.devze.com 2023-03-07 17:52 出处:网络
I have the following HTML: <div class=\"accordion\"> <h3>My title</h3> <div>My content</div>

I have the following HTML:

<div class="accordion">
  <h3>My title</h3>
  <div>My content</div>
  <h3>My title</h3>
  <div>My content</div>
  <h3>My title</h3>
  <div>My content</div>
</div>

What I need to do via jQuery is wrap each of the h3's and div's in another div class="myDiv", so the final output would look like:

<div class="accordion">
  <div class="myDiv">
    <h3>My title</h3>
    <div>My content</div>
  </div>
  <div开发者_Python百科 class="myDiv">
    <h3>My title</h3>
    <div>My content</div>
  </div>
  <div class="myDiv">
    <h3>My title</h3>
    <div>My content</div>
  </div>
</div>

How would I do this with jquery?


Try this:

$("h3").each(function(){
   $(this).next("div").andSelf().wrapAll("<div class='myDiv'></div>");
});

http://jsfiddle.net/BSQpf/


Something like this should do it:

$('.accordion h3').each(function() {
    $(this).nextUntil('h3').andSelf().wrapAll('<div class="myDiv"/>');
});

jsFiddle example

See the API:

  • nextUntil
  • andSelf
  • wrapAll
0

精彩评论

暂无评论...
验证码 换一张
取 消