I want to group every 2 images in a different div but leaving the wider ones with only one image. That's the HTML:
<figure id="container">
<img src="001.jpg" class="single" />
<img src="002.jpg" class="single" />
<img src="003.jpg" />
<img src="004.jpg" />
<img src="005.jpg" />
<img src="006.jpg" />
<img src="007.jpg" />
<img src="008.jpg" class="single" />
<img src="009.jpg" />
<img src="010.jpg" class="single" />
</figure>
So, I don't know what jQuery scripts to use to group these respecting the class "single", the wider ones. I want:
<figure id="container">
<div><img src="001.jpg" class="single" /></div>
<div><img src="002.jpg" class="single" /></div>
<div><img src="003.jpg" />
<img src="004.jpg" /></div>
<div><img src="005.jpg" />
<img src="006.jpg" /></div>
<div><img src="007.jpg" /></div>
<div><img src="008.jpg" class="single" /></div>
<div><img src="009.jpg" /></div>
<div><img src="010.jpg" class="single" /></div>
</figure>
Now that I fully understand your question, there's a function below that should work to suit your needs.
Here' what the function does:
container
and check each if they have class single
.single
then check the next element too. Wrap just the first one, or both if the second one is also not a single
.single
.Here's the code with runnable snippet:
$(function() {
var skip = false;
$('#container img').each(function() {
var $this = $(this);
if (!skip && $this.is(":not(.single)")) {
var $next = $this.next('img');
if ($next.is(".single")) {
skip = false;
$this.wrapAll("<div/>");
} else {
skip = true;
$this.add($next).wrapAll("<div/>");
}
} else {
skip = false
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<figure id="container">
<img src="001.jpg" class="single" />
<img src="002.jpg" class="single" />
<img src="003.jpg" />
<img src="004.jpg" />
<img src="005.jpg" />
<img src="006.jpg" />
<img src="007.jpg" />
<img src="008.jpg" class="single" />
<img src="009.jpg" />
<img src="010.jpg" class="single" />
</figure>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments