Is there an “exists” function for jQuery?

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

    There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:

    if(document.getElementById("myElement")) {
        //Do something...
    }
    

    If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.

    jQuery is really cool, but don't let pure JavaScript fall into oblivion...

提交回复
热议问题