views:

50

answers:

5

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?

+1  A: 

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

meder
+1  A: 

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
    }
}
HoLyVieR
+1 for good old vanilla js ;)
john_doe
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.
meder
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.
john_doe
+2  A: 

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.

Daniel Vassallo
+1  A: 

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

if($('#someObject')[0])
Robusto
A: 

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');
}
Russ Cam