tags:

views:

74

answers:

3

Hello,

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.

+2  A: 

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

$("a[href*='.png']").addClass("image-link");
Andrew Hare
+2  A: 

Hey.

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"]')
meder
Do I know you Meder? Haha!Yeah it was a damn typo.
Amir
A: 

Try this:

var aFileExts = new Array("png", "jpg", "fig");
for(aIndex in aFileExts) {
    aFileExt = aFileExts[aIndex];
    $("a[href$='.".aFileExt."']").addClass("image-link");
}

Hope this helps.

NawaMan