Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap adjacent elements with the same class [duplicate]

I need to wrap adjacent elements with the same class in a div using jQuery. So far I'm using .wrapAll function to wrap elements with the same class in a div.

HTML:

<a class="image"></a>
<a class="image"></a>
<a class="image"></a>
<p>Some text</p>
<a class="image"></a>
<a class="image"></a>

Script:

$( "a.image" ).wrapAll( "<div class='gallery'></div>" );

Output:

<div class='gallery'>
    <a class="image"></a>
    <a class="image"></a>
    <a class="image"></a>
    <p>Some text</p>
    <a class="image"></a>
    <a class="image"></a>
</div>

However I need to wrap the adjacent elements with 'image' class in separate divs with 'galley' class. So the output needs to look like this:

<div class='gallery'>
    <a class="image"></a>
    <a class="image"></a>
    <a class="image"></a>
</div>
<p>Some text</p>
<div class='gallery'>
    <a class="image"></a>
    <a class="image"></a>
</div>

Is there a way to do this using jQuery?

like image 549
Anna Avatar asked Jan 05 '16 11:01

Anna


1 Answers

  1. You get the non adjacent images (the first and the one just after the p) by using .not function.
  2. For each of them you collect the adjacent image by using (.nextUntil and andSelf).
  3. Finally you wrap them all using .wrapAll

$('.image').not('.image+.image').each(function(){
  $(this).nextUntil(':not(.image)').andSelf().wrapAll('<div class="gallery" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="image">1</a>
<a class="image">2</a>
<a class="image">3</a>
<p>Some text</p>
<a class="image">4</a>
<a class="image">5</a>

http://jsbin.com/gonino/edit?html,js

Update This is the result of the snippet.

enter image description here

like image 176
Mosh Feu Avatar answered Oct 07 '22 10:10

Mosh Feu