views:

20090

answers:

7

I am using jQuery, I want to check existence of an element in my page. I have done following code, but its not working?

if ($("#btext" + i) != null){
        //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

Please tell me what will be the right code?

Thanks

+6  A: 

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 may just do nothing.

$("#btext" + i).text("Branch " + i);
tvanfosson
0 is a false value, so the elem.length expression evaluates to false - in other words, there is no need for the '!= 0' part
J-P
+27  A: 

Check the jQuery FAQ...

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

if ( $('#myDiv').length ){}
Christoph
Thanks, its really very good.
Prashant
+5  A: 

jquery $() function always return non null value - mean elements matched you selector cretaria. If lement not found it return empty array. So your code will look something like this -

if ($("#btext" + i).length){
        //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}
waney
Nice. You always learn something new.
marko
A: 
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]

J-P
A: 
if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}
한지만
+1  A: 

no matter what you selection is the function $() always returns a jQuery object so that cant be used to test. The best way yet (if not the only) is to use the size() function or the native length property as explained above.

if ( $('selector').size() ) {...}

burntblark