Adding 'rel' attribute with setAttribute

I’m trying to integrate the Lightbox plugin into a clients CMS. This should be easy, all I need to do is find the <a> surrounding thumbnail images (the CMS automatically gives these the class ‘gs_image_link’) and use Javascript to add the rel=‘lightbox’ attribute that triggers the Lightbox plugin.

I have the following being linked to in a seperate .js file:

window.onload = function() {
addRelFunction();
}

function addRelFunction() {
// get all <a> tags
var allLinks = document.getElementsByTagName(“a”);
// Cycle through all <a> tags
for (var i=0; i<allLinks.length; i++) {
// get the ‘class’ of the current <a> tag
var title_text = allLinks[i].getAttribute(“class”);
// if the current <a> tag has a class of ‘gs_image_link’, add rel=‘lightbox’
if (title_text == “gs_image_link”) {
allLinks[i].setAttribute(“rel”, “lightbox”);
// pop up alert to let me know it has added the rel
alert(allLinks[i].getAttribute(“rel”));
};
};
};

My code so far isn’t doing what I expect, on a page with 2 '<a class=“gs_image_link”>'s I get two pop up alerts telling me they now have a rel of ‘lightbox’ but when viewing the source the rel has not been added.

Any help on where I’m going wrong?

Don’t use getAttribute - it breaks for the class attribute in older versions of IE (fixed in IE8 I think). I would just do this:

var allLinks = document.body.getElementsByTagName('a');
for (var i = 0, j = allLinks.length; i < j; i++) {
  if (allLinks[i].className === 'gs_image_link') {
    allLinks[i].rel = 'lightbox';
  }
}

If you view the source, it won’t be added. This is because “view source” just gives you the original HTML downloaded from the server. To see the HTML after javascript has done stuff to it, in Firefox you need to select a section of the page (or do ctrl+A) then select “view selection source” in the context menu.

Thanks, I just checked with Firebug element inspector and the rel=‘lightbox’ was indeed being added after all! The lightbox still wasn’t working but I worked out this is due to my code loading after the Lightbox plugin code when it needed to add the rel attribute before.

Thanks!