Phillip Whisenhunt
Phillip Whisenhunt

Reputation: 1305

Using jQuery to select direct child of div

I am trying to select a direct child of an element. For example, given a DOM structured as:

<div class="track">
   <div class="a"></div>
   <div class="b"></div>
</div>
<div class="track">
   <div class="a"></div>
   <div class="b"></div>
</div>
<div class="track">
   <div class="a"></div>
   <div class="b"></div>
</div>

When a user clicks on say the first track div, how can I grab the immediate a and b underneath it?

I've tried using

$(this).children(".a");

$(this).find(".a");

but it always grabs references to the very bottom track instead. Any help is very much appreciated! Thanks!

Edit: My problem lied in another section of my code where I was temporarily referencing a track. Therefore, when I would click on a track, it would reference a different track. Thank you all for your help though!

Upvotes: 0

Views: 581

Answers (3)

Pavan
Pavan

Reputation: 4339

You may want to check out jsfiddle.

Upvotes: 1

Wasim Karani
Wasim Karani

Reputation: 8886

Jsfiddle Reference

$(".track").click(function(){
    alert($(this).children(".a").html());
    alert($(this).children(".b").html());
})

Upvotes: 2

maxedison
maxedison

Reputation: 17573

Your use of children() is correct, so the problem must be in your broader implementation, involving the .click() handler. Can you post more of your code?

This kind of thing would work:

$('.track').click(function(){
   var trackChildren = $(this).children(); //will get you .a and .b for whichever .track was clicked
});

Upvotes: 2

Related Questions