Determining whether jQuery has not found any element

后端 未结 4 1302
执笔经年
执笔经年 2020-12-07 21:17

I\'m using jQuery\'s selectors, especially id selector:

$(\"#elementId\")...

How should I determine whether jQuery has found the element or

相关标签:
4条回答
  • 2020-12-07 21:57
    $('#my_selector').length > 0 
    $('#my_selector').get(0) !== undefined
    $('#my_selector')[0] !== undefined
    

    This is the basic, now do whatever you want.

    0 讨论(0)
  • 2020-12-07 22:03

    Futuraprime is right but you can shorten your syntax by doing the following:

    if ($("#id").length) {
       //at least one element was found
    } else {
       //no elements found
    }
    
    0 讨论(0)
  • 2020-12-07 22:08

    $('#idThatDoesnotexist').length is what you're looking for. (If it finds nothing, this will === 0.) So your conditional statement should probably be:

    if($('#id').length) { /* code if found */ } else { /* code if not found */ }

    You're getting an object returned from that alert because jQuery (almost) always returns the "jQuery object" when you use it, which is a wrapper for the elements jQuery's found that permits method chaining.

    0 讨论(0)
  • 2020-12-07 22:21
    !$.isEmptyObject($.find('#id'))
    

    This will return true if the element exists and false if it doesn't.

    0 讨论(0)
提交回复
热议问题