0

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?

2
  • 1
    no it would have nothing to do with whether its empty or not. double check your selector Commented Jun 3, 2015 at 15:54
  • 3
    FYI: .length is a property not a function! Commented Jun 3, 2015 at 15:56

2 Answers 2

5

.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
}
Sign up to request clarification or add additional context in comments.

Comments

2
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

4 Comments

<0 will always return false.
Thanks all - I have updated the original post with the code but it's returning the same result whether there is a div with that id in the document or not. Is their a better way to check if an element exists or not not using jQuery?
check out the edit...in the if condition check for the "html()", it should be jQuery('#myDiv').html().length
Doh - I was using the if condition OUTSIDE of the (document).ready function. Have just moved it inside and it's all working fine. Feel so silly. Thanks for your help, much appreciated :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.