1

I have seen lot of questions like this but none of them helped me I want to see when my span tag get available in DOM, my code looks like this

   <span id="inviteUpdate">0</span>

    if(jQuery("#inviteUpdate").html()>0){
        alert("Element exists");
    }

Am I missing something here?

10
  • Try jQuery("#inviteUpdate").html().length
    – hjpotter92
    Commented Sep 21, 2014 at 7:36
  • if(jQuery('#inviteUpdate').length) { // Your span is in DOM } Commented Sep 21, 2014 at 7:37
  • @ViktorBahtev That doesn't work, jQuery objects are always truthy, even if they're empty.
    – Barmar
    Commented Sep 21, 2014 at 7:37
  • stackoverflow.com/questions/3086068/… looking for this ?
    – Rahul Dess
    Commented Sep 21, 2014 at 7:38
  • @hjpotter92 didn't worked , also I got this on console Uncaught TypeError: Cannot read property 'length' of undefined
    – Badddy
    Commented Sep 21, 2014 at 7:40

3 Answers 3

2

If you want to test whether an element exists in the DOM, use .length:

if ($("#inviteUpdate").length > 0) {
    alert ("Element exists");
}

This is because jQuery collections can be used as arrays, returning the original DOM elements that were matched.

2

You can use getElementById method. If the value is not null, it exists.

var span1 = document.getElementById('inviteUpdate');
if(span1 != null)
{
    alert('span exists');
}

works well.

1

  if(jQuery("#inviteUpdate").length >0){
        alert("Element exists");
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<span id="inviteUpdate">0</span>

check this

1
  • The clause jQuery("#inviteUpdate") cannot be falsy. The first part of the condition serves no purpose.
    – Kijewski
    Commented Sep 21, 2014 at 7:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.