If I have a bunch of links to an image like this:
<a href="foo.png">foo.png</a> <a href="foo.jpg">foo.jpg</a> <a href="foo.gif">foo.gif</a>
How would I find it all with js and then add a class?
This is what I was thinking but that didn't work:
$('a[href*=.png]').addClass('image-link');
$('a[href*=.jpg]').addClass('image-link');
$('a[href*=.gif]').addClass('image-link');
UPDATE: There was a typo in my js. The above works.
Your first way targeted just the png and worked fine in FF 3.5, your updated way seems to work too.
$('<a href="foo.png">foo.png</a> <a href="foo.jpg">foo.jpg</a> <a href="foo.gif">foo.gif</a>').appendTo('body')
$('a[href]').filter(function() {
return /(jpg|gif|png)$/.test( $(this).attr('href'))
}).addClass('image-link')
alert( $('.image-link').length )
You sure you're doing this on DOM ready, and that you're targeting the right stuff, no typos?
$('<a href="foo.png">foo.png</a> <a href="foo.jpg">foo.jpg</a> <a href="foo.gif">foo.gif</a>').appendTo('body')
$('a[href*=".png"]').addClass('image-link');
$('a[href*=".jpg"]').addClass('image-link');
$('a[href*=".gif"]').addClass('image-link');
alert( $('.image-link').length )
^ this alerted 3 for me as well.
Updated: More concise selector would be..
$('a[href*=".png"], a[href*=".gif"], a[href*=".jpg"]')
Try something like this (notice the single quotes around .png
):
$("a[href*='.png']").addClass("image-link");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With