Is there a 'not found' exception for jquery selector?

后端 未结 4 1417
孤街浪徒
孤街浪徒 2021-01-18 08:56

I just spent \'hours\' with the following scenario: (all back to the basics)

 $(\'#typo\').bind(\'click\' etc ...

I had a typo in the selec

4条回答
  •  天涯浪人
    2021-01-18 09:41

    You can use the length of the returned DOM elements as a falsy and throw a new error like so:

    var el = '#el';
    
    if ($(el).length){
        // Do Stuff
    } else {
        throw new Error("Element "+el+" Doesn't Exist");
    }
    

    OR

    // Ignores Empty Selector
    if ($('#el').length){
        // Do Stuff
    }
    

    I hope this helps!

提交回复
热议问题