简体   繁体   中英

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?

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.

如果你正在寻找一个ID,那么它应该只有一个,所以你也可以这样写:

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

是的, .length是可以接受的,通常是我使用的。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM