admin管理员组

文章数量:1201801

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?

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?

Share Improve this question edited Oct 10, 2010 at 13:53 alex 490k204 gold badges889 silver badges991 bronze badges asked Oct 10, 2010 at 13:42 Isaac LubowIsaac Lubow 3,5735 gold badges40 silver badges57 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 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
    }
}

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.

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

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

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

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

本文标签: javascriptHow to check for the presence of an elementStack Overflow