Reputation:
So I am trying to traverse through multiple elements and I seem to be having a problem. I have 2 divs that have two child elements each - an input and a link. Inside the link there is also an image. When I click on the input button of the first div, I want to be able to traverse to it's sibling(the link{a tag}) and into the links child(the img tag) and get its source attribute which I will then use to change the image of the second div. Here's an excerpt of the code
HTML:
<div id="item">
<a href="#" target="_blank" id="yeezy"><img src="img/deli/1.jpg" alt="Owl Image" id="homeimage"></a>
<input type="submit" id="btn1" class="btn btn-default dropdown-toggle viewbuttons" value="View Item" onclick='changeImage( "img/deli/1.jpg" );'>
</div>
<div class="item">
<a href="#" target="_blank"><img src="img/deli/2.jpg" alt="Owl Image" id="homeimage"></a>
<input type="submit" id="btn" class="btn btn-default dropdown-toggle viewbuttons" value="View Item" onclick='changeImage( "img/deli/2.jpg" );'>
</div>
JQUERY:
$(document).ready(function(e){
$('input#btn1').on('click', function(){
var changeThis = $('input#btn1').siblings('#yeezy').children('img').attr('src');
$("#homeimage").attr("img", changeThis);
})
});
Thank you in advance
Upvotes: 1
Views: 399
Reputation: 144729
IDs must be unique. ID selector only selects the first matching element in the document. You are getting/setting src
attribute of one element, i.e. both $('input#btn1').siblings('#yeezy').children('img')
and $("#homeimage")
refer to the same element.
Either use different IDs or use class attributes. Also note that since IDs must be unique, $('input#btn1').siblings('#yeezy')
doesn't make a lot of sense. You could simply select the element using an ID selector: $('#yeezy')
;
Upvotes: 1
Reputation: 1428
There are a few things off with your code. You use the id "homeimage" twice, but there should only ever be one of a given id. You have the onclick attributes set to a different function besides the one you want to run, so you should remove those. Finally, when you try to change the src attribute of the homeimage, you call the function on the img attr: ("img", changeThis);
Make sure that all of your ID's are unique, remove any onclick atrributes from your elements, and then replace:
$("#homeimage").attr("img", changeThis);
with:
$('#homeimage').attr('src', changeThis);
Upvotes: 0