javascriptjquerychildrenwrapall

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


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>


Solution

  • Remove # from your HTML ids.

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