Is there an “exists” function for jQuery?

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

    I'm using this:

        $.fn.ifExists = function(fn) {
          if (this.length) {
            $(fn(this));
          }
        };
        $("#element").ifExists( 
          function($this){
            $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});               
          }
        ); 
    

    Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/

提交回复
热议问题