javascript - Wrap all elements up until :nth-child -


i having hard time figuring out, sure simple.

i know have use :nth-child count every set of elements want wrap. wondering how count :nth-child , wrap previous elements including :nth-child in div each set of elements match :nth-child. assuming there .each() involved.

the code laid out so:

<div class="wrapper">  <h3>heading</h3> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a>  <h3>heading</h3> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a>   <h3>heading</h3> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a>   <h3>heading</h3> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> </div> 

update tried piece of code , seems give me desired results, stops @ 16.

  $(".wrapper").each( function () { $(this).children(":lt(16)").wrapall("<div></div>") }); 

jquery's .each() function has built in index - can use our advantage select every 16 elements.

$("div.wrapper").children().each(function(i){     if(i % 16 == 0 && != 0){         // elements need wrap, they're going in reverse order (thanks .prevall())         var elementstowrap = $(this).prevall().not('.wrap2');         var temp = [];         for(var j=0; j < elementstowrap.size(); j++){             // reverse objects selected placing them in temporary array.             temp[(elementstowrap.size()-1) - j] = elementstowrap.eq(j)[0];         }         // wrap array jquery object, use .wrapall() add div around them         $(temp).wrapall('<div class="wrap2" />');     } }); 

demo http://jsfiddle.net/crz7e/1/

if wanted wrap each element separately - instead of group, don't need reverse selection, , use .wrap()


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -