Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all image links and add a class to it

Tags:

jquery

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.

like image 966
Amir Avatar asked Nov 13 '09 06:11

Amir


2 Answers

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"]')
like image 150
meder omuraliev Avatar answered Nov 12 '22 13:11

meder omuraliev


Try something like this (notice the single quotes around .png):

$("a[href*='.png']").addClass("image-link");
like image 31
Andrew Hare Avatar answered Nov 12 '22 15:11

Andrew Hare