开发者

jQuery: Wrap only first and second child, not the rest of children

开发者 https://www.devze.com 2023-01-14 14:37 出处:网络
In my actual code: <div id=\"mother\"> <div id=\"child-01\"></div> <div id=\"child-02\"></div>

In my actual code:

<div id="mother">
  <div id="child-01"></div>
  <div id="child-02"></div>
  <div id="child-03"></div>
  </ul>

I need to produce:

<div id="mother">
  <div id="myWrap">
    <div id="child-01"></div>
    <div id="child-02"></div>
  </div>
  <div id="child-03"><开发者_JAVA技巧;/div>
  </ul>

I was playing with wrap, .wrapAll() and children, but I'm stuck.

If in my actual code i have:

<div id="mother">
  <div id="child-01"></div>
  <div id="child-02"></div>
  <div id="child-03"></div>
  </ul>

  <div id="uncle">
    <div id="cousin-01"></div>
    <div id="cousin-02"></div>
    <div id="cousin-03"></div>
    </ul>

How do i produce:

<div id="mother">
  <div id="myWrap">
    <div id="child-01"></div>
    <div id="child-02"></div>
    <div id="cousin-02"></div>
  </div>
  <div id="child-03"></div>
  </ul>


First as Adam said remove the # prefix from your id attributes. Also match your closing tags, currently you have a </ul> where a </div> should be.

Then, you can do it using :lt() and .wrapAll() like this:

$("#mother div:lt(2)").wrapAll("<div id='myWrap'></div>");

This gets everything less than index 2 (0 and 1 are the first 2), then wraps it. You can test it here.


Remove # from your HTML ids.

$("#mother div:eq(0), #mother div:eq(1)").wrapAll("<div id='father'></div>")


sharp should not be part of the id's. Then you can do:

$('#child-01, #child-02').wrapAll('<div id="#mywrap" />');


$(document).ready(function(){
  $(".new-grid__item:nth-child(1), .new-grid__item:nth-child(2)").wrapAll('<div class="child"></div>');
});
0

精彩评论

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