Create new image element using the src of image in another div using jquery

StackOverflow https://stackoverflow.com/questions/22535186

  •  18-06-2023
  •  | 
  •  

Вопрос

<div id='show-image'></div>
<div class='post'>
<div class='inner'>
<img class='post-img' src='http://3.bp.blogspot.com/-Sg5t3utxRzc/UwgyzbLVAAI/AAAAAAAAFBo/vYQX0Cphx8U/s1600/indian-bride.jpg'/>
</div>
</div>

Okay so what I want is that I want to get the src of the image .post-img and want to create a new image element inside the div id='show-image'

I would be glad if anyone can help me to achieve this using jQuery

Это было полезно?

Решение

You can use .attr() to get the src of your image then .append() to append newly created image with retrieved src to the div with id show-image:

var src = $('.post-img').attr('src');
$('#show-image').append('<img src="' + src + '" />');

or you can use .appendTo():

var url=$('.post-img').attr("src"); 
$('<img src="'+url+'" />').appendTo('#show-image');

Другие советы


Just another way of writing it

var newImg = $("<img>", { 
                src: $(".post-img").attr("src") 
            });
$("#show-image").append(newImg);

Try this:

var img = $('<img>');
img.attr('src', $("img.post-img").attr("src"));
img.appendTo('#show-image');

DEMO

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top