Is there an “exists” function for jQuery?

前端 未结 30 3021
野性不改
野性不改 2020-11-21 04:52

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}
<         


        
30条回答
  •  野的像风
    2020-11-21 05:04

    The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:

    if (document.getElementById('element_id')) {
        // Do something
    }
    

    It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.

    And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.

    NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).

提交回复
热议问题