views:

46

answers:

1

I have barely any experience working with DOM and using Javascript, and I have a very specific task that I'm trying to accomplish.

Let's say I have an image in my HTML:

<img src="foo.jpg" />

When the site loads, I want to take that image (all images in the document, actually), and wrap them in a link:

<a href="http://www.foobar.com"&gt;&lt;img src="foo.jpg" /></a>

What could I use to accomplish this? Google hasn't turned up much for me with regards to this specific task. On load, I can access and iterate all the images in the document... but I'm not sure where to go from there in order to wrap the image in a link.

+2  A: 

You could try something among the lines:

window.onload = function() {
    var images = document.getElementsByTagName('img');
    for (var i = 0, image = images[i]; i < images.length; i++) {
        var wrapper = document.createElement('a');
        wrapper.setAttribute('href', 'http://www.foobar.com');
        wrapper.appendChild(image.cloneNode(true));
        image.parentNode.replaceChild(wrapper, image);
    }
};

I would recommend you using the excellent jQuery library to manipulate the DOM:

$(function() {
    $('img').wrap('<a href="http://foo.com"&gt;');
});
Darin Dimitrov
+1 didn't know about replaceChild, and my own plain js version didn't work very well when I tested it =)
David Hedlund