Is there an “exists” function for jQuery?

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

    Is $.contains() what you want?

    jQuery.contains( container, contained )

    The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

    Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

提交回复
热议问题