1

I'm trying to read all links on the page and check if link extension is ending with '.png'. If it does, then when that link is clicked, I want to grab that image and append into div with the class 'test'. If link doesn't end with '.png' just ignore it and open normally.

This is markup, you can grab it on jsFiddle too:

<a href="image01.png">Image 01</a>
<a href="image02.png">Image 02</a>
<a href="http://www.google.com/">Page</a>
<a href="image03.png">Image 03</a>

<div class="test"></div>

... and this is how markup should look like when first link is clicked:

<a href="image01.png">Image 01</a>
<a href="image02.png">Image 02</a>
<a href="http://www.google.com/">Page</a>
<a href="image03.png">Image 03</a>

<div class="test">
  <img src="image01.png" />
</div>

Thanks!

Klikerko
  • 1,097
  • 2
  • 11
  • 28

2 Answers2

2

Try this

$("a[href$='.png']").click(function(e){
   e.preventDefault();
   $(".test").append("<img src='"+this.href+"' />");
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
2

Here is a complete and quite elegant (imho) combination of the posted examples, errors and other stuff fixed

$('a[href$=".png"]').click(function(e) { // nice one ChristopheCVB
    $('.test').append($("<img>", {src: this.href})); // neater than "<img src='"+...+">"
    e.preventDefault(); // should be enough
});

Demo here

Next we need a test to see if image is already there...

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Thanks mplungjan, I selected your reply as accepted solution although I have to say @ShankarSangoli was first one with complete solution. – Klikerko Jul 18 '11 at 18:54
  • I decided to combine since one was more elegant that the other. For example the src:this.href instead of string concatenation - everybody has now edited their solutions so they all resemble each other more than before – mplungjan Jul 18 '11 at 19:07