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

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?

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

First you can select the html element with jquery, and then use the html () method to set the desired html. Here is an example:

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

The only thing you should be able to uniquely identify the desired div that you want to change. Perhaps setting id or class.

+2
source

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

+2
source

First you need to find out if there is a wrap element where you want to enter this content. In jquery you should use a function:

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

Suppose 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 a class of ".inner" will now be added with 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 the jquery documentation to find out more: http://api.jquery.com/append/

+2
source

This works by adding an image object.

 $('<a>', {href:''}).append($('<img>', {src:''}).appendTo('body') 
+1
source

Source: https://habr.com/ru/post/906138/


All Articles