alias51
alias51

Reputation: 8648

How to select a child from a parent div in Jquery

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

Answers (6)

Nick
Nick

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

$(".d").click(function(){
    alert($('div[class="a"]').children(":first").text());
});

this will select the element with class b.

Live Demo

This will also work

$(".d").click(function(){
    alert($(this).parent().parent().children(":first").text());
});

Live Demo 2

Even this

$(".d").click(function(){
    alert($(this).parent().prev('div').text());
});

Live Demo 3

Upvotes: 0

Udit Bhardwaj
Udit Bhardwaj

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

$(".d").click(function(){
    $(this).parent().prev('div'); // or $(this).closest('.b'); 
});

Updated after OP's comment

fiddle DEMO

$(".d").click(function(){
    $(this).parent().parent().children().first();
});

Reference

.closest()

.parent()

.prev()

Upvotes: 0

Šime Vidas
Šime Vidas

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:

  • event delegation is used,
  • the query within the handler is local, restricted to the page component.

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

colbydauph
colbydauph

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

Related Questions