如何检查元素的存在?

Isa*_*bow 4 javascript jquery

.length在条件语句中使用该方法,该方法轮询页面是否存在外部加载的对象(我不能使用jQuery对其进行样式直到它存在):

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

length是最好的方法吗?

HoL*_*ieR 11

如果您只是寻找特定元素,您可以使用 document.getElementById

function hackyFunction() {
    if (document.getElementById("someObject")) {
         // Exist
    } else {
         // Doesn't exist
    }
}
Run Code Online (Sandbox Code Playgroud)