简体   繁体   中英

jQuery check if exists using empty element

Is it possible to check if an element exists in jQuery using the length function, even though the element is empty?

I have an empty div <div id="myDiv"></div> that gets populated by AJAX when the user scrolls to a certain point on the screen, but when I try targeting the div before that point I'm getting nothing. The code I'm using is…

if( jQuery('#myDiv').length) {
    alert('#myDiv exists!');
} else {
    alert('#myDiv doesn\'t exist!');
}  

but I'm wondering if the reason it isn't selecting the div is because it's empty. Does that matter when using the length function?

.length is not a method. It is a property, so remove the () after it.

if( jQuery('#myDiv').length ) {
    // If the div exists do this
} else {
    // If it doesn't do this
}
length is a `property` and not a `function`. It should be

if( jQuery('#myDiv').length) {
    alert('#myDiv exists!');
} else {
    alert('#myDiv doesn\'t exist!');
} 

It should be the below codes assuming you want to check whether the div is empty or not

if( jQuery('#myDiv').html().length > 0){
 // If the div is empty do this
}
else{
  // If its not empty do this
}

Check the jQuery DOCS

EDIT: Check if you have used the if condition inside document ready . Check out the fiddle

jQuery('#myDiv').html().length > 0

Here is the Fiddle Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM