neethu neethu - 5 months ago 14
Javascript Question

How to select an image having particular 'alt' attribute using jquery

I have the below html in my page .

<div id="bb-bookblock" class="bb-bookblock bb-vertical" style="height: 578.24885475px">
<div class="bb-item" style="display: none;">
<a href="#">
<img src="photorepository/admin/a-123/14/31 copy_200comp.jpg" alt="31 copy_200comp.jpg" style="height:100%">
</a>
</div>
<div class="bb-item" style="display: none;">
<a href="#"><img src="photorepository/admin/a-123/14/32 copy_200comp.jpg" alt="32 copy_200comp.jpg" style="height:100%"></a>
</div>
<div class="bb-item" style="display: none;">
<a href="#"><img src="photorepository/admin/a-123/14/4 copy_200comp.jpg" alt="4 copy_200comp.jpg" style="height:100%"></a>
</div>
<div class="bb-item" style="display: none;">
<a href="#"><img src="photorepository/admin/a-123/14/5 copy_200comp.jpg" alt="5 copy_200comp.jpg" style="height:100%"></a>
</div>
</div>


I need to turn style="display: block;" of the div having class 'bb-item' of the image having a particular alt .for example if the alt is '5 copy_200comp.jpg'.Then the parent div of that particular image turn like this:

<div class="bb-item" style="display: block;"> <a href="#"><img src="photorepository/admin/a-123/14/5 copy_200comp.jpg" alt="5 copy_200comp.jpg" style="height:100%"></a></div>


I tried the code :
var src = $('img[alt="example"]')
something like this but not working.Please help

Answer

You could use :has() selector as follow.

$('.bb-item:has(img[alt="5 copy_200comp.jpg"])').show();

The selector .bb-item:has(img[alt="5 copy_200comp.jpg"]) will select the element having class bb-item having an image inside it with the specified alt attribute value.

Demo