Reputation:
I want to achieve going to the parent element then to the prev element get the atrribute id of the element which has class: classname.
<div>
<span><span id="190" class="classname">blabla</span></span>
<span><a href="#" class="button">blabla</a></span>
</div>
Pseudo code:
$('.button').click(function(){
console.log($(this).parent().prev().$(".classname").attr("id"));
});
Do I have to use a find here or is there another way?
Upvotes: 2
Views: 781
Reputation: 3045
Maybe you could use the context feature, like so:
$('.button').click(function(){
console.log( $('.classname', $(this).parent() ).attr('id') );
});
Upvotes: 0
Reputation: 1635
as Ivanfosson has stated, you can use his advice only if you know the finite number of steps or layers down DOM the element you are searching, but if the <div>
you placed is relative to some other divs and you can also use find
and then do
$(this).parent().prev().children( '.classname' ).attr( 'id' );
Upvotes: 0
Reputation: 35
By the way, the id "190" is invalid, id and name attributes must begin with a letter, not a digit.
Upvotes: 1
Reputation: 28391
Find seems like the shortest way to get there....
alert($(this).parents("div").find(".classname").attr( 'id' ));
or
alert($(this).parents("div").find("span span").attr( 'id' ));
Upvotes: 0
Reputation: 532445
For your example:
$(this).parent().prev().children( '.classname' ).attr( 'id' );
Upvotes: 4