Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for the presence of an element?

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?

like image 492
Isaac Lubow Avatar asked Nov 29 '22 19:11

Isaac Lubow


2 Answers

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
    }
}
like image 188
HoLyVieR Avatar answered Dec 05 '22 15:12

HoLyVieR


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.

like image 42
Daniel Vassallo Avatar answered Dec 05 '22 15:12

Daniel Vassallo