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
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')
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()
try this code:
$("#parent").click(function () {
$(this).next().hide();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With