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?
p
) by using .not
function..nextUntil
and andSelf
)..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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With