Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap multiple div elements on same class

I would like to use jQuery to wrap sets of class elements in a div but can't find the solution.

HTML:

<div class="view-content">

  <div class="first">content</div>
  <div class="first">content</div>
  <div class="second">content</div>
  <div class="third">content</div>
  <div class="third">content</div>

</div>

Desired Result:

<div class="view-content">

  <div class="column">
    <div class="first">content</div>
    <div class="first">content</div>
  </div>

  <div class="column">
    <div class="second">content</div>
  </div>

  <div class="column">
    <div class="third">content</div>
    <div class="third">content</div>
  </div>

</div>
like image 283
Matthias O. Avatar asked Jun 05 '12 11:06

Matthias O.


3 Answers

Demo http://jsfiddle.net/kQz4Z/8/

API: http://api.jquery.com/wrapAll/

Added a break line so that you can see the difference here :) http://jsfiddle.net/kQz4Z/10/

code

$(function() {

    $('.first').wrapAll('<div class="column" />')

    $('.second').wrapAll('<div class="column" />')

    $('.third').wrapAll('<div class="column" />')




    alert($('.view-content').html());
});​
like image 66
Tats_innit Avatar answered Nov 15 '22 13:11

Tats_innit


Use wrapAll() method

$(function(){
    var classes = ['.first', '.second', '.third'];

    for (i = 0; i < classes.length; i++) {
        $(classes[i]).wrapAll('<div class="column">');
    }​

});

Demo: http://jsfiddle.net/g9G85/

like image 32
charlietfl Avatar answered Nov 15 '22 11:11

charlietfl


Or here is the very short dynamical solution:

​$(".view-content > div").each(function() {
    $(".view-content > ." + this.className).wrapAll("<div class='column' />");
});​

DEMO: http://jsfiddle.net/CqzWy/

like image 2
VisioN Avatar answered Nov 15 '22 12:11

VisioN