Is there an “exists” function for jQuery?

前端 未结 30 3001
野性不改
野性不改 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

    Checking for existence of an element is documented neatly in the official jQuery website itself!

    Use the .length property of the jQuery collection returned by your selector:

    if ($("#myDiv").length) {
        $("#myDiv").show();
    }
    

    Note that it isn't always necessary to test whether an element exists. The following code will show the element if it exists, and do nothing (with no errors) if it does not:

    $("#myDiv").show();
    

提交回复
热议问题