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

▼魔方 西西 提交于 2019-12-24 17:00:04

问题


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"></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>

回答1:


Remove # from your HTML ids.

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



回答2:


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.




回答3:


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

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



回答4:


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


来源:https://stackoverflow.com/questions/3638122/jquery-wrap-only-first-and-second-child-not-the-rest-of-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!