Reputation: 481
Please, i know that probabily this is a really easy question, but no matter what i try i can't make it work. I have few divs with the same class on my page, and i would like to show only divs that have an image inside. Can someone help please?
<div class="one">
<div class="two"><img src="some.jpg" /></div> <!-- show this -->
<div class="two"><img src="some_other.jpg" /></div> <!-- show this -->
<div class="two"></div> <!-- hide this -->
</div>
Upvotes: 3
Views: 1440
Reputation: 268424
You could base your selector on the images themselves, and from there traverse back up to the parents and toggle their visibility. One way would be to use the $.fn.parent
method:
$(".two img").parent().show();
This approach is fairly quick, taking just under 3ms for me. The above demonstrates the execution path.
Alternatively, you could select all of the .two
instances, and then filter that collection based on the presence of img
elements using the $.fn.has
function:
$(".two").has("img").show();
This method is a bit more involved, judging by the flame chart above, and took roughy 5ms compared to the quicker alternative above. You could alternative use the pseudo-selector :has
, however this would mean you could no longer take advantage of performance optimizations that leverage querySelectorAll
.
The above approaches assume .two
elements are hidden initially. If this is not the case, the following could achieve this for you:
$(".two").hide().has("img").show();
This approach selects all instances of .two
, hides them, filters that selection to only those that have an img
element among their children, and show's the resulting set.
Flame charts based on jQuery 2.0.2 in Chrome 32
Upvotes: 2
Reputation: 913
This is incredibly easy with straight JavaScript not to mention a lot faster:
var images = document.querySelectorAll('.two');
for (var i = 0; i < images.length; i++) {
var self = images[i];
if (!self.childNodes[0]) {
self.style.display = 'none';
}
}
Upvotes: 1
Reputation: 144719
You can use the :has
selector:
$('.two').hide().filter(':has(img)').show();
Upvotes: 3