Drew
Drew

Reputation: 1261

jquery how do I get an imgs src

I have a gallery and I have some code setup like so

$('.gallery img').click(function(){
    $('#gal_img').html('<img src=""/>');
});

this has a lot of other things running that dont matter, but I want it to get the img src from the ".gallery img" is placed into the new img. I have multiple images inside the .gallery div

Upvotes: 2

Views: 136

Answers (4)

Felix
Felix

Reputation: 38102

You can use either .attr():

$('.gallery img').click(function(){
    var src = $(this).attr('src');
    $('#gal_img').html('<img src="' + src + '"/>');
});

or .prop() to get the src attribute of an image:

$('.gallery img').click(function(){
    var src = $(this).prop('src');
    $('#gal_img').html('<img src="' + src + '"/>');
});

As @Vision suggestion you can also use pure javascript this.src

$('.gallery img').click(function () {
    $('#gal_img').html('<img src="' + this.src + '"/>');
});

Upvotes: 6

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

You can also use the .prop()

$('img').prop('src') 

Sample JSFIDDLE

Or else you may simply try this:

$('.gallery img').click(function(){
    $('#gal_img').html('<img src="' + this.src + '"/>');
});

Upvotes: 2

Jai
Jai

Reputation: 74738

You can do this:

$('.gallery img').click(function(){
   var img = $('<img />', {'src' : this.src});
   $('#gal_img').html(img);
});

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can also do just like this (the fastest solution):

$('.gallery img').click(function(){
    $('#gal_img').html('<img src="' + this.src + '"/>');
});

Upvotes: 1

Related Questions