Add Attributes to Links via jQuery

Posted by on Jan 5, 2011 in Development, jQuery | No Comments

I was working on a recent project that used a lightbox-style jQuery plugin called Facebox. This allowed me to put both images and DIVs of content into a lightbox-style popover — simply add rel=“facebox“ to an anchor tag and it would activate the popover.

The one thing Facebox didn’t do “out of the box” was automatically make links to images open in the lightbox window. To fix this, I just used a bit of jQuery to add rel=“facebox“ to any anchor tag that linked to a JPG or PNG:

// add rel="facebox" to image links for lightbox effect
$("a[href$=.jpg],a[href$=.jpeg],a[href$=.png]").attr("rel","facebox");