admin管理员组

文章数量:1317123

<ul id="bad-drifting">
    <li>text</li>
</ul>

/

jQuery(document).ready(function() { 
    if (jQuery('#bad-drifting').has('em')) {
        jQuery('#bad-drifting').css({'color': 'red'});
        jQuery('#bad-drifting').css({'font-weight': 'bold'});
    }
});

/

jQuery(document).ready(function() { 
    if (jQuery('#bad-drifting li:has(em)')) { // .has('em')
        jQuery('#bad-drifting').css({'color': 'red'});
        jQuery('#bad-drifting').css({'font-weight': 'bold'});
    }
});

What I want to do is not just set some CSS but make more plicated changes but I can't figure out why this always returns true... Is it a bug or what am I missing?

<ul id="bad-drifting">
    <li>text</li>
</ul>

http://jsfiddle/wZ8MC/2/

jQuery(document).ready(function() { 
    if (jQuery('#bad-drifting').has('em')) {
        jQuery('#bad-drifting').css({'color': 'red'});
        jQuery('#bad-drifting').css({'font-weight': 'bold'});
    }
});

http://jsfiddle/Xzn6y/

jQuery(document).ready(function() { 
    if (jQuery('#bad-drifting li:has(em)')) { // .has('em')
        jQuery('#bad-drifting').css({'color': 'red'});
        jQuery('#bad-drifting').css({'font-weight': 'bold'});
    }
});

What I want to do is not just set some CSS but make more plicated changes but I can't figure out why this always returns true... Is it a bug or what am I missing?

Share Improve this question asked Apr 29, 2013 at 11:26 OZZIEOZZIE 7,39810 gold badges62 silver badges63 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

That's because has returns a jQuery object and an object is a truthy value in JavaScript, you should use length property:

if (jQuery('#bad-drifting').has('em').length) {

You need to check for length because jQuery('#bad-drifting li:has(em)') returns a jQuery object which will be always truthy.

if (jQuery('#bad-drifting li:has(em)').length) { // .has('em')
if (jQuery('#bad-drifting').has('em')[0]) { // do Stuff

I ended up doing like this:

if (jQuery('#bad-drifting em').length > 0) {
    console.log('we have some errors');
}   

Check the length of your jQuery "collection":

 if (jQuery('#bad-drifting li:has(em)').length > 0) { // There is at least one element

otherwise it will always be true, because what jQuery returns is always truthy.

本文标签: javascriptjQuery if has() selector do stuffStack Overflow