How to create link element with image as anchor with jquery?

19,519

Solution 1

$('<img />').attr({
  src:'some image url',
  width:'width in intiger',
  height:'integer'
}).appendTo($('<a />').attr({
  href:'somelink'
}).appendTo($('#someElement')));

Solution 2

You can first select the html element using jquery and then use the "html()" method to set the desired html. Here is a sample:

$('div.demo-container')
  .html('<a href=""><img src="" /></a>');

The only thing is that you should be able to uniquely identify the desired div that you want to alter. Probably by setting id or class.

Solution 3

Well.. you can do: $('<a href="http://mysite.com"><img src="/img/img.jpg" /></a>').appendTo('#myDIV')

Solution 4

First you need to figure out if there is a wrapping element around where you would like to inject this content. In jquery you would use the function:

$('.inner').append('<p>Test</p>');

Lets say this was your dom element:

<h2>Greetings</h2>
  <div class="container">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
</div>

Any items with the class ".inner" will now be appended a paragraph with the word "test"

<h2>Greetings</h2>
  <div class="container">
    <div class="inner">
      Hello
      <p>Test</p>
    </div>
    <div class="inner">
      Goodbye
      <p>Test</p>
    </div>
 </div>

Check out jquery's documentation to find out more: http://api.jquery.com/append/

Solution 5

This works by appending an image object.

$('<a>', {href:''}).append($('<img>', {src:''}).appendTo('body')
Share:
19,519
user979390
Author by

user979390

Updated on July 02, 2022

Comments

  • user979390
    user979390 almost 2 years

    I know how to create elements with jquery using something like:

    $('<div/>').appendTo('body');
    

    How can I create this:

    <a href=""><img src="" /></a>
    

    Using the same technique?