Need to find <a> tags with <img> tags in them

I really know nothing about how to code JavaScript (I know what it is and what it does) and I need a script to go in the head of my page and look for all <a> tags that have <img> tags inside of them and add a rel=“lightbox” attribute to them. Could someone please show me how to do this?

Because that syntax only works correctly on objects. It can process unwanted elements if you try to use it on arrays or nodelists.

I totally agree, using standard javascript will load much faster.

I was suggesting that as a javascript newbie, jQuery might be a great library for him to learn.

In the two examples above using standard javascript, all <img> within <a> tags will be grabbed. There maybe, I would assume, some images that he might not want to use lightbox on. In that case, adding a class to the <a> would help.

Why use a standard for loop, when a foreach-style syntax exists?

var a = document.getElementsByTagName('a');
for (i in a) {
    var img = a[i].getElementsByTagName('img');
    for (j in img){
       img[j].rel = 'lightbox';
    }
}

Just shortens things a bit :stuck_out_tongue:

Thanks. When I learn JavaScript I think I’m going to be use JQuery and the JQueryUI library.

This is what I’ll probably use just to reduce page load time. I’ll let you know how it works.

Or the much shorter regular JavaScript equivalent added immediately before the </body> tag of:

var a = document.getElementsByTagName('a');
for (var i = 0, l = a.length; i < l; i++) {
   var img = a[i].getElementsByTagName('img');
   for (var j = 0, k = img.length; j < k; j++) {
      img[j].rel = 'lightbox';
   }
}

That’s way less than 0.1% of the size of the script using jQuery.

I would highly recommend using jQuery. It is a very easy java script library to use and understand for beginners.

Visit http://jquery.com/ for more information.

Using jQuery you can grab any page element with the following:

$(‘a.lightbox’);
Grabs all <a> with the class ‘lightbox’. The a is the element and the .lightbox is the class. You grab classes with “.” and id’s with “#”.

$(‘a#foo’);
Grabs the <a> with the id ‘foo’

$('#footer a ');
Grabs all <a> within the element with the id ‘footer’

In your situation to grab all <a> with an <img> and add a attribute to them you do this:
$(‘a img’).attr({‘rel’: ‘lightbox’});

To add this to the head you’ll need to do two things.
First
Add a reference to the jQuery library. Copy this and add it to the head of your site.
<script type=“text/javascript” src=“http://code.jquery.com/jquery-1.4.2.min.js”></script>
Second
Add this code below the jquery reference.
<script>
$(document).ready(function() {
$(‘a img’).attr({‘rel’: ‘lightbox’});
});
</script>

It is a very simple way of grabbing page elements. There are many lightbox examples on the jQuery site as well.

Good luck!