How to check null objects in jQuery

Prashant picture Prashant · Jan 25, 2009 · Viewed 397k times · Source

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) != null) {
    //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

How do I check the existence of the element?

Answer

Christoph picture Christoph · Jan 25, 2009

Check the jQuery FAQ...

You can use the length property of the jQuery collection returned by your selector:

if ( $('#myDiv').length ){}