Checking if two divs contain content, and if not adding a class to their container div
I am trying to check whether two child divs contain content and if t开发者_StackOverflowhey do not ie they are empty then I would like to add a class to their parent div. This is my code but this adds the class="noBorder" to the parent div if the child divs are empty or not.
if(('div.nav-previous:empty') && ('div.nav-next:empty')) {
jQuery('div#nav-below').addClass('noBorder')
};
Any help with this would be much appreciated.
Gina
That's because a jQuery selector will always return a value, regardless of whether it matched anything.
$('.this-doesnt-exist') // returns []
The above will return an empty array which will evaluate to TRUE.
Whenever you want to check if jQuery has returned a set of elements, you must check the length property:
if( $('.this-doesnt-exist').length == 0 ) {
alert('it didnt exist!');
}
Your if() statement is nonsensical. Technically, it is asking
if(true && true) {
//do stuff
}
I presume what you want to do is check to see if two elements are in fact empty and then apply a style. In that case you would do:
if($('div.nav-previous:empty').length !=0 && $('div.nav-next:empty').length != 0) {
jQuery('div#nav-below').addClass('noBorder')
};
The if() statement will now be asking:
- Are there any
<div class="nav-previous">
that are empty, and - Are there any
<div class="nav-next">
that are empty?
If you have more than one nav-previous and nav-next, then this might look different, but that doesn't seem to be the case.
I solved it by doing some more investigation: Here is the code that worked
if (jQuery('.nav-previous').is(':empty') && jQuery('.nav-next').is(':empty'))
{
jQuery('div#nav-below').addClass('noBorder');
};
NOTE: :empty selector only works if there are no brs or spaces within the divs.
精彩评论