Reputation:
I have code similar to the following:
<div class="class1">
<a class="link1" src="...">...</a>
</div>
<div class="class2">
<a class="link2" src="...">...</a>
</div>
Assuming I am currently in the click event for class link2, how do do I get the src value of the link1 hyperlink? These are dynamically generated so there may be many instances of this code so I would need to traverse the dom from $this to get to link1. Thanks.
Upvotes: 1
Views: 347
Reputation: 4278
A flexible solution might be if you added a common identifier to the divs you are calling class1 and class2, you could find your parent's previous sibling. For example, instead of your HTML, you could have:
<div class="class1 someClass">
<a class="link1 someLink" src="...">...</a>
</div>
<div class="class2 someClass">
<a class="link2 someLink" src="...">...</a>
</div>
And then, in an onclick function on all your links, for example,
$('a.someLink').click(function() {
var $someContainer = $(this).parents('someClass:first');
var $prevContainer = $someContainer.prev();
// now you can work with $prevContainer ...
});
You would of course first want to check whether a "prev" sibling really does exist or not. You could adapt to the find the next, etc.
Good luck!
-f!
Upvotes: 1
Reputation: 70414
$('a.link2').click(function() {
console.log($(this).parent().prev('div.class1').children('a.link1'));
});
Upvotes: 4