CSS and jQuery both have limitations in achieving that particular task. One approach is to utilize the closest
method.
$(function(){
var element = $('#parent').children('#child');
if (element.closest('.foo').length > 0) {
//you will get true for .foo, #child, or #parent, or div, ...
console.log('Yay!');
} else {
console.log('Duh!');
}
});
This code snippet prints 'Yay' when executed.
The mentioned method checks if the element itself or any ancestor has the specified class. It is possible to check for a class or an ID. To verify hidden elements, consider using the :hidden
pseudo-selector with the regular is
function instead of hasClass
. View this example Fiddle Here:
<div id="parent" class="foo" style='display: none'>
<div id="child">
</div>
</div>
$(function(){
var element = $('#parent').children('#child');
if (element.is(':hidden')) {
console.log('Yay!');
} else {
console.log('Duh!');
}
});
This code also outputs 'Yay' upon execution.
An alternative method can be implemented based on your current DOM structure. Refer to this Fiddle Here:
$(function(){
var element = $('#parent').children('#child');
if (element.is('.foo *')) {
console.log('Yay!');
} else {
console.log('Duh!');
}
});
Executing this code snippet will result in printing 'Yay' as well.
Considering the presence of ng-hide
, typically associated with AngularJS, it's advisable to refrain from solely relying on jQuery and reconsider the problem at hand unless you are specifically creating a custom directive.