JS / jQuery: how can I automatically exchange <a href> tags around <img /> s when href is dynamic based on img src?

Heads up: I am completely new to Javascript, and so far I have written only basic jQuery-based scripts. I learn fast though ...

What I get is the way:

1) define tags

2) read img tags

3) wrap the tag with the <a href> tag with a dynamic link based on src img.

Example:

 <img src="../../img_T/Culture/C_01/c_01_abb_005.jpg" width="310" height="180" alt="image1"> 

should become

 <a href="../../img_L/Culture/C_01/c_01_abb_005.jpg"><img src="../../img_T/Culture/C_01/c_01_abb_005.jpg" width="310" height="180" alt="C 01 Abb 005"></a> 

I think that reading the src of each image and writing it to a variable, then reading that variable and replacing / img _T / with / img_L /, and then writing this to a new variable, which can then be simply added to each HREF.

Here's how far I got it, but that doesn't work at all:

 /* in the comments 'xxx' represents a different unique image string */ /* This should get the <img src="../img_T/xxx" /> string as text and store it. */ var $imgSrc = $(".displaywrapper img").attr("src"); /* This part should use the above sourced <img src="../img_T/xxx" string and replace ../img_T/ of the src with ../img_L/ and store it in var = imgLink. */ var imgLink = $imgSrc.text().replace("img_T","img_L"); /* This part should then wrap the <img src="../img_T/xxx" /> so it becomes <a href="..img_L/xxx"><img src="../img_T/xxx" /></a> */ $(".displaywrapper img").each(function(){.wrap("<a href="imgLink"></a>")}); 

Thank you for reading. Jannis

+4
source share
2 answers

I think this should do the trick:

 $(document).ready(function() { $(".displayWrapper img").each(function() { var src = $(this).attr('src').replace('img_T','img_L'); var a = $('<a/>').attr('href', src); $(this).wrap(a); }); }); 

Line 1: Wait for the document to be ready before doing anything ..
Line 2: Scrolling through each image using the jQuery each function.
Line 3: Get the current src image with attr and replace img_T with img_L
Line 4: Dynamically create new <a> tag and set its href attribute to src on line 3
Line 5: wrap the <a> tag around the <img > tag.

+21
source

If you only need images that can be clicked, do the following:

 $(".displayWrapper img").click(function(){ document.location.href = this.src.replace("img_T", "img_L"); }); 
+3
source

All Articles