How to check null objects in jQuery

后端 未结 13 859
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: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);
    

提交回复
热议问题