6
 <li id ="pdf1"> <img id ="pfd1img" src="/Content/img/pdf.png"/>Catalogue</li>

script:

 $("#pdf1img").attr('href', '/Content/pdf/' + data.pdf1);

I'm trying to add a hyperlink to an image. I think I'm nearly there, but am I missing something?

MauriceNino
  • 6,214
  • 1
  • 23
  • 60
Beginner
  • 28,539
  • 63
  • 155
  • 235

2 Answers2

26
$("#pdf1img").wrap($('<a>',{
   href: '/Content/pdf/' + data.pdf1
}));

Try that ^^^

Image elements cannot be links, but they can be wrapped in anchor elements which are.

.wrap() in jQuery Docs

Naftali
  • 144,921
  • 39
  • 244
  • 303
8

img elements do not have href attributes. If you want the image to act as a link you have a couple of options. You could wrap the img in an a element:

$("#pdf1img").wrap("<a href='/Content/pdf/" + data.pdf1 + "'>");

Or you could bind a click event handler to the image and use window.location:

$("#pdf1img").click(function() {
    window.location.href = "/Content/pdf/" + data.pdf1;
});
James Allardice
  • 164,175
  • 21
  • 332
  • 312