0

I want to turn every <img> into a link to itself (the file) via an external js file.

My thought process was that I could target all img elements, then grab the image src and place a link to it around the img element. For example:

Turning this:

<img width="281" vspace="7" hspace="5" height="215" align="left" alt="img1" src="cits/images/image001.jpg"></img>

Into this:

<a href="cits/images/image001.jpg" target="_blank">
<img width="281" vspace="7" hspace="5" height="215" align="left" alt="img1" src="cits/images/image001.jpg"></img>
</a>

It looks like I can grab the img src as a variable as well as find the img element, but I'm not sure how I could go about adding the link around the img.

3
  • 3
    I'd use another approach: handle clicks on all the images as if they are links (using window.open, if you want them to be opened in the separate window). The problem is, wrapping all images in <a> element may disrupt the structure of your page. Commented Feb 26, 2013 at 16:28
  • @raina77ow That sounds a lot easier, thanks. I'm going to leave this up for a bit incase anyone has more ideas to throw out or solutions. Commented Feb 26, 2013 at 16:29
  • @ Richard Dalton No, I'm only using javascript right now. I'm open to jquery, but I'm new to js, haven't done much in jquery. Commented Feb 26, 2013 at 16:30

3 Answers 3

3

Grab all your images.

var images = document.getElementsByTagName('img');

Write a function that replaces the outerHTML of an image with new markup, including a link pointing to the src attribute of the image, which includes the old outerHTML of the image.

function makeLink(image){
    image.outerHTML = '<a target="_blank" href="' + image.src + '">' + image.outerHTML + '</a>';
}

Loop through your images, and submit each one to the makeLink function.

for(var i = 0, l = images.length; i < l; ++i){
    makeLink(images[i]);
};
Sign up to request clarification or add additional context in comments.

Comments

2

Just in case you are using jQuery

$('img').each(function(ix, image){
  $(image).wrap('<a target="_blank" href="' + $(image).attr('src') + '"></a>');
})

Comments

1

If you're willing to use jQuery, the code is very simple:

$("img").each(function () {
    $(this).wrap($("<a target='_blank'/>").attr("href", $(this).attr("src"));
});

Otherwise you're gonna have to look into a raw JavaScript solution, which is a bit more elaborate. See @Barney's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.