How to check null objects in jQuery

后端 未结 13 852
Happy的楠姐
Happy的楠姐 2020-11-30 17:24

I\'m using jQuery and I want to check the existence of an element in my page. I have written following code, but it\'s not working:

if($(\"#btext\" + i) != n         


        
相关标签:
13条回答
  • 2020-11-30 18:14

    What about using "undefined"?

    if (value != undefined){ // do stuff } 
    
    0 讨论(0)
  • 2020-11-30 18:17
    if ( $('#whatever')[0] ) {...}
    

    The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties; one of them being a "length" property. You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, i.e. $(elem)[0]

    0 讨论(0)
  • 2020-11-30 18:20

    Using the length property you can do this.

    jQuery.fn.exists = function(){return ($(this).length < 0);}
    if ($(selector).exists()) { 
       //do somthing
    }
    
    0 讨论(0)
  • 2020-11-30 18:23

    use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)

    0 讨论(0)
  • 2020-11-30 18:23
    if (typeof($("#btext" + i)) == 'object'){
        $("#btext" + i).text("Branch " + i);
    }
    
    0 讨论(0)
  • 2020-11-30 18:26

    The lookup function returns an array of matching elements. You could check if the length is zero. Note the change to only look up the elements once and reuse the results as needed.

    var elem = $("#btext" + i);
    if (elem.length != 0) {
       elem.text("Branch " + i);
    }
    

    Also, have you tried just using the text function -- if no element exists, it will do nothing.

    $("#btext" + i).text("Branch " + i);
    
    0 讨论(0)
提交回复
热议问题