Jquery this child selector?

hey, quick question, I could not find anything on the Internet. I have a parent div and a child div inside it. To select it using css, you would say:

#parent .child {} 

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

 var Parent = $('#parent'); Parent.click(function() { $(this > '.child').hide(); 

Thank you

+8
jquery parent
source share
5 answers

The correct syntax is:

 $(".child", this) 

If you need only direct children:

 $("> .child", this) 

(credit refers to Gumbo to mention this)

Update after two years:

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

+23
source share

You can simply call the .find() method:

 var Parent = $('#parent'); Parent.click(function() { $(this).find('.child').hide(); }); 

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

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

People often use type syntax

 $('.child', this); 

and. This is not very convenient for me, since you write the "reverse" order. Anyway, this syntax is converted internally to the .find() operator, so you actually save the call.

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

+6
source share

try this code:

  $("#parent").click(function () { $(this).next().hide(); }); 
+1
source share
 var Parent = $('#parent'); Parent.click(function () { $(".child", this).hide(); }); 

or

 $("#parent").click(function () { $(".child", this).hide(); }); 
+1
source share

U can find the children of your parents and apply css.

Sample code below.

 var Parent = $('#parent'); Parent.click(function() { $(this).find('.child').hide();}); 
+1
source share

Source: https://habr.com/ru/post/650305/


All Articles