Reputation: 8648
I have the following HTML:
<div class="a">
<div class="b"></div>
<div class="x"></div>
<div class="y"></div>
<div class="c">
<div class="d"></div>
</div>
</div>
When I call $(".d").click(function(){
, how can I select div class .b? I want to do this relatively, without using the .b
class name.
Upvotes: 0
Views: 203
Reputation: 4212
You have to find parent
previous sibling
$(".d").click(function(){
$(this).parent().prev();
})
if you want to set the third sibling before current parent simply append three times prev() ex.
$(".d").click(function(){
$(this).parent().prev().prev().prev();
})
Upvotes: 0
Reputation: 9947
$(".d").click(function(){
alert($('div[class="a"]').children(":first").text());
});
this will select the element with class b.
This will also work
$(".d").click(function(){
alert($(this).parent().parent().children(":first").text());
});
Even this
$(".d").click(function(){
alert($(this).parent().prev('div').text());
});
Upvotes: 0
Reputation: 1781
$(.d).click(function(){
$(this).parent().siblings('.b') //in this way
})
there are many ways for doing this for them you can refer to jquery website http://api.jquery.com/category/selectors/
Upvotes: 0
Reputation: 57105
$(".d").click(function(){
$(this).parent().prev('div'); // or $(this).closest('.b');
});
Updated after OP's comment
$(".d").click(function(){
$(this).parent().parent().children().first();
});
Reference
Upvotes: 0
Reputation: 186083
The standard approach:
$('.module').on('click', '.button', function () {
$('.other', this)...
});
Where:
.module
is the outer-most (wrapper) element of the page component,.button
is the element within the component whose click actions you're listening to,.other
is the element you're selecting within the click handler.Notice how:
Also, notice how the other answers are hard-coding the element relationship in jQuery (those parent()
and sibling()
calls) which is not a good approach.
Upvotes: 1
Reputation: 364
It depends on whether or not their relative positions will always stay the same.
If b is always going to be d's parent's previous sibling, you can select it with the following:
$('.d').on('click', function(){
var b = $(this).parent().prev();
});
If b is always going to be d's parent's parent's first child:
$('.d').on('click', function(){
var b = $(this).parent().parent().find(">:first-child");
});
Upvotes: 0