Reputation: 2139
I'm trying to search for specific text in an image alt tag and add CSS to that image using jQuery. I'm using the :contains
from jQuery, but I'm not sure if that's the best way to go about it? This is what I'm trying so far:
jQuery
var imgAlt = $("img").attr("alt");
$("imgAlt:contains('morning hike')").css("border", "5px solid black");
HTML:
<div>
<img src="https://images.unsplash.com/photo-1584879788725-56a4b394de8d?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="candles on table">
<img src="https://images.unsplash.com/photo-1584354012731-ba34cef5963f?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="morning hike">
</div>
Hope that makes sense?
Upvotes: 1
Views: 105
Reputation: 2118
You don't necessarily need javascript, the selector can be created using just css attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
img[alt*='morning hike'] { border: 5px solid #000 }
We could use the same selector in your jQuery
$("img[alt*='morning hike']").css("border", "5px solid black");
Upvotes: 2