noclist
noclist

Reputation: 1819

combining jQuery objects

I have an image and I have a link. How can I use jQuery to make a linked image like this:
<a href="src"><img src="src"></a>

var image = $('<img>').attr('src', src);
var link = $('<a>').attr('href', src);

Upvotes: 0

Views: 24

Answers (2)

Barmar
Barmar

Reputation: 780974

Use the append() method.

link.append(image);

Upvotes: 3

Mikey
Mikey

Reputation: 6766

$(function () {
  var src = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a';
  var href = 'https://stackoverflow.com/';
  
  var img = $('<img/>').attr('src', src);
  var link = $('<a/>').attr('href', href);
  
  // just set the content of the link to the image
  link.html(img);
  
  $('body').append(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Upvotes: 2

Related Questions