简体   繁体   中英

How to add wrapper div for 2 child divs (all child divs having same class)

I am having one div with four child divs with same class..all habving same class..I want two wrap 2 divs inside one parent div..I cant add through html or add any classes because its coming from drupal template ..is there any way to add seperate wrapper divs for first two and last two divs ..thanks in advance

 $( ".myclass" ).wrapAll( "<div class='row' />"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <div class="row"> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div> </div> 

As I understand, you want to wrap the first two elements inside another new row right?

This should do it:

 var elements = $( ".myclass" ); $([elements[0], elements[1]]).wrapAll( "<div class='row' />"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <div class="row"> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div> </div> 

That should do it.

Use :lt() selector

Description: Select all elements at an index less than index within the matched set.

This means select all element with index less than 2 which is first and second element which has index of 0 and 1 respectively

 $(".myclass:lt(2)").wrapAll("<div class='row' />"); 
 .row { color: red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <div class="myclass">1</div> <div class="myclass">2</div> <div class="myclass">3</div> <div class="myclass">4</div> 

You can use slice .

 $('.myclass').slice(0,2).wrapAll( "<div class='row' />"); $('.myclass').slice(2,4).wrapAll( "<div class='row' />"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <div class="row"> <div class="myclass">1</div> <div class="myclass">2</div> <div class="myclass">3</div> <div class="myclass">4</div> </div> 

Alternatively, you can use this:

$('.myclass:eq(0),.myclass:eq(1),').wrapAll('<div class="row1"></div>');
$('.myclass:eq(2),.myclass:eq(3),').wrapAll('<div class="row2"></div>');

In the above example, I have used the :eq() selector to select the children div's. In this method, indexing starts from 0 (just like arrays).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM