Reputation: 44293
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 variable for my parent element. However, how can I select the child with this? I know it's easy to create a new variable, I'm just curious if it's possible?
const parent = $('#parent');
parent.click(function() {
$(this > '.child').hide();
})
thank you
Upvotes: 7
Views: 23172
Reputation: 31524
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')
Upvotes: 22
Reputation: 8463
U can find children of your parent elements and apply css.
Sample code is below.
var Parent = $('#parent');
Parent.click(function() {
$(this).find('.child').hide();});
Upvotes: 1
Reputation: 235972
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()
Upvotes: 6
Reputation: 8638
var Parent = $('#parent');
Parent.click(function () {
$(".child", this).hide();
});
or
$("#parent").click(function () {
$(".child", this).hide();
});
Upvotes: 1
Reputation: 3257
try this code:
$("#parent").click(function () {
$(this).next().hide();
});
Upvotes: 1