Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery this child selector?

Tags:

jquery

parent

hey, quick question, i couldn't find anything on the web. I have a parent div and a child div inside of it. to select it with css you would say:

#parent .child {}

In jquery I have a var for my parent element, however how can i select the child with this? I know it's easy to create a new var, i'm just curious if it's possible?

var Parent = $('#parent');

Parent.click(function() {
$(this > '.child').hide();

thank you

like image 641
matt Avatar asked Dec 20 '10 08:12

matt


3 Answers

The correct syntax is:

$(".child", this)

If you only want the direct children:

$("> .child", this)

(credit goes to Gumbo for mentioning this)

Update, two years later:

You can use $(this).find('> .child')

like image 83
Gabi Purcaru Avatar answered Nov 02 '22 13:11

Gabi Purcaru


You may just invoke the .find() method:

var Parent = $('#parent');

Parent.click(function() {
    $(this).find('.child').hide();
});

If you only want to select the immediate children, use the .children() method instead:

Parent.click(function() {
    $(this).children('.child').hide();
});

People often use a syntax like

$('.child', this);

aswell. It's not very convinient to me since you write a "reverse" order someway. Anyway, this syntax gets converted internally into a .find() statement, so you're actually saving a call.

Ref.: .find(), .children()

like image 25
jAndy Avatar answered Nov 02 '22 13:11

jAndy


try this code:

  $("#parent").click(function () {
               $(this).next().hide();
});
like image 32
AEMLoviji Avatar answered Nov 02 '22 12:11

AEMLoviji