Reputation: 213
I would like to check if a element has a children with a class.
So I used:
$('input:checkbox, input:radio').on('click', function() {
if($(this).children().hasClass('sub-question')) {
alert('Yes');
}
else {
alert('No');
}
});
My HTML is the following:
<div class="form-group">
<label>Item A
<input type="radio">
</label>
</div>
<div class="form-group">
<label>Item B
<input type="radio">
</label>
<div class="row sub-question">
<div class="form-group">
<label class="container_radio">Sub level 1
<input type="radio">
</label>
</div>
</div>
</div>
But it doesn't work.
Could you please help me with this ?
Thanks.
Upvotes: 0
Views: 2115
Reputation: 173
In your example any of the elements selected by 'input:checkbox, input:radio'
has children.
You can do something like traversing up through its ancestors until find the .sub-question
element using the .closet method
$('input:checkbox, input:radio').on('click', function() {
if($(this).closest('.form-group').find('.sub-question').length > 0) {
alert('Yes');
}
else {
alert('No');
}
});
Upvotes: 1
Reputation: 82231
this
refers to context of the checkbox/radio button. You need to traverse to closest form-group and then use .find()
selector with length to check if element exists :
if($(this).closest('.form-group').find('.sub-question').length > 0) {
alert('Yes');
}
else {
alert('No');
}
Upvotes: 2