4

I'm using the .length method in a conditional statement that polls the page for the presence of an externally-loaded object (I can't style it with jQuery until it exists):

function hackyFunction() {
  if($('#someObject').length<1)
  { setTimeout(hackyFunction,50) }
  else
  { $('#someObject').someMethod() }}

Is length the best way to do this?

5 Answers 5

12

If you are simply looking for a specific element you can just use document.getElementById

function hackyFunction() {
    if (document.getElementById("someObject")) {
         // Exist
    } else {
         // Doesn't exist
    }
}
2
  • 1
    I don't agree. If you have multiple checks for an element, the script will be filled with gEBI functions, which is useless if you're already including the entire jQuery library. Not to mention, in that specific snippet you'd have to invoke it twice unless you're not caching it before the if..else. And if you use gEBI all over the place you have to remember to wrap jQuery around it or unless you invoke prototypal methods, they will not be defined. Commented Oct 10, 2010 at 13:53
  • 1
    You're absolutly right, but...^^ In the code snippet from the TO are two jquery-objects invoked for the same element. Also the TO has had selected the 'javascript'-tag only. For this, the vanilla-js solution is absolutely appropriate.
    – Andreas
    Commented Oct 10, 2010 at 14:54
4

Yes you should use .length. You cannot use if ($('#someObject')) ... because the jQuery selectors return a jQuery object, and any object is truthy in JavaScript.

3

Yes, .length is acceptable and is usually what I use.

3

If you're looking for an ID there should only ever be one of those, so you could also write:

if($('#someObject')[0])
1

With jQuery, checking length works fine.

if (!$('#someObject').length) {
    console.log('someObject not present');
}

Of course with vanilla JavaScript, you can just check with document.getElementById (if getting elements by id)

if (document.getElementById('someObject')) {
    console.log('someObject exists');
}

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