jinfy
jinfy

Reputation: 157

how to wrap every divs using jquery?

I tried to wrap every .test1 and .test2 class into one div tag but its wrapping whole div class. Please suggest.

HTML

<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>

Excepted:

<div class="container">
    <div class="test1">This is demo paragraph1.</div>
    <div class="test2">This is demo paragraph2.</div>
</div>
<div class="container">
    <div class="test1">This is demo paragraph1.</div>
    <div class="test2">This is demo paragraph2.</div>
</div>
<div class="container">
    <div class="test1">This is demo paragraph1.</div>
    <div class="test2">This is demo paragraph2.</div>
</div>

Jquery:

$(".test1, .test2").wrapAll("<div class="container"></div>");

Upvotes: 0

Views: 50

Answers (2)

skobaljic
skobaljic

Reputation: 9614

You can go this way, using CSS adjacent sibling combinator (+) for quick selection:

$('.test1 + .test2').each(function() {
    $(this).prev().addBack().wrapAll('<div class="container" />');
});
.container {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>

Also on JSFiddle.

Please note, for older versions of jQuery, instead of addBack() method, should use andSelf().

Upvotes: 1

random_user_name
random_user_name

Reputation: 26150

  1. The quotation marks in your jQuery ("<div class="container"></div>") are causing an error.
  2. Be sure to run this in a document ready function
  3. The clarified expectation is a bit trickier, but possible assuming there are always groups of two, using the addBack function.

This Fiddle shows one way to make it work, based on the assumptions above:

// no-conflict safe shorthand document ready
jQuery(function($) {
  $(".test1").each(function() {
      $(this).next(".test2").addBack().wrapAll('<div class="container"></div>');
  });
});

Upvotes: 1

Related Questions