$('div.thumbnail').each(function () {
var $this = $(this),
count = $this.find('img').length;
$this.after('<h2>', {
text: 'Contains (' + count + '*) image' + (count == 1 ? '' : 's')
});
});
Count images or "rel" attribute
Question
I´d like to count all images for one <div class="thumbnail">
separately.
My code:
<div class="thumbnail">
<a rel="first" href="#">
<div>
<div></div>
<img src="...">
</div>
</a>
<div class="hidden-fb"> <!-- // CSS display: none -->
<a rel="first" href="#">
<div>
<div></div>
<img src="...">
</div>
</a>
</div><!-- .hidden-fb -->
</div><!-- .thumbnail -->
<h2>Contains 2* images </h2>
I try this
var featureImageCount = $('div.thumbnail img').length;
$('div.thumbnail').after('<div><h1>' + featureImageCount + ' Images</h1></div>');
But I get just for all divs "(6)"
Can I do this with jquery, that the number* of images will be automatically fill out?
Or can jquery count the items by different rel
attributes?
Thanks
Ogni
Solution 2
OTHER TIPS
You need to look at each .thumbnail
element individually, using .each
. Then, you can use $(this)
in the callback to access the actual element. From there, you can find all specific descendent <img>
elements. From there, you can just use .after
like you attempt to, with $(this)
.
$(document).ready(function () {
$("div.thumbnail").each(function () {
var $this = $(this),
count = $this.children("a").children("img").length;
$this.after("<div><h1>" + count + " Images</h1></div>");
});
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow