178

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?

lorem monkey
  • 3,942
  • 3
  • 35
  • 49
djmzfKnm
  • 26,679
  • 70
  • 166
  • 227

13 Answers13

258

Check the jQuery FAQ...

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

if ( $('#myDiv').length ){}
Pang
  • 9,564
  • 146
  • 81
  • 122
Christoph
  • 164,997
  • 36
  • 182
  • 240
65

(Since I don't seem to have enough reputation to vote down the answer...)

Wolf wrote:

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!

Instead try this:

 // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE!  -- EleotleCram
if($("#something") !== null){
  // do something
}

or

 // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE!  -- EleotleCram
if($("#something") === null){
  // don't do something
}

While it is true that calling the length property on an undefined or null object will cause browsers to fail, the result of jQuery's selectors (the $('...')) will never be null or undefined. Thus the code suggestions make no sense. Use one of the other answers, they make more sense.


(Update 2012) Because people look at code and this answer is pretty high up the list: For the last couple of years, I have been using this small plugin:

  jQuery.fn['any'] = function() {
     return (this.length > 0);
  };

I think $('div').any() reads better than $('div').length, plus you won't suffer as much from typos: $('div').ayn() will give a runtime error, $('div').lenght will silently most likely always be falsy.

__
Edits november 2012:

1) Because people tend to look at code and not read what is said around the code, I added two big caveat lector notes to the quoted code of Wolf.
2) I added code of the small plugin I use for this situation.

Xavier Egea
  • 4,712
  • 3
  • 25
  • 39
eleotlecram
  • 1,194
  • 12
  • 9
  • 2
    @VovaPopov : I suggest next time you take a little more time to read the answer. I was merely stating that the code example "by Wolf" was incorrect. I never provided an answer, just referred to some of the other answers which make more sense. – eleotlecram Nov 01 '12 at 18:25
  • Good answer. I'm sorry people misinterpret it. – Joe Simmons Sep 20 '13 at 12:44
16

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);
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 7
    0 is a false value, so the elem.length expression evaluates to false - in other words, there is no need for the '!= 0' part – James Jan 25 '09 at 15:06
  • 2
    @999, I think the check against zero makes the code more readable, although both ways are likely readable to someone who's used to scripting languages. – Sam Aug 10 '12 at 08:38
12

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

if ($("#btext" + i).length){
        //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}
cchana
  • 4,899
  • 3
  • 33
  • 43
waney
  • 402
  • 1
  • 5
  • 20
  • 1
    I don't think it's true that the $() returns an array. jQuery objects have behaviours that are similar to arrays, but I don't think they are actually arrays, and I think you'll find that not all of their behaviour is the same as that of arrays. See [this quick demonstration](http://jsfiddle.net/CuR9z/). – Sam Aug 10 '12 at 08:24
5

What about using "undefined"?

if (value != undefined){ // do stuff } 
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Hugh Seagraves
  • 594
  • 1
  • 8
  • 14
5

In jQuery 1.4 you get the $.isEmptyObject function, but if you are forced to use an older version of jQ like us poor Drupal developers just steal use this code:

// This is a function similar to the jQuery 1.4 $.isEmptyObject.
function isObjectEmpty(obj) {
  for ( var name in obj ) {
    return false;
  }
  return true;
}

Use it like:

console.log(isObjectEmpty(the_object)); // Returns true or false.
BenMorel
  • 34,448
  • 50
  • 182
  • 322
theamoeba
  • 1,331
  • 13
  • 14
4

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() ) {...}                   
Gwenc37
  • 2,064
  • 7
  • 18
  • 22
burntblark
  • 124
  • 1
  • 4
3
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]

James
  • 109,676
  • 31
  • 162
  • 175
1

Using the length property you can do this.

jQuery.fn.exists = function(){return ($(this).length < 0);}
if ($(selector).exists()) { 
   //do somthing
}
Suresh Pattu
  • 6,083
  • 16
  • 59
  • 91
1

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 :)

kamaci
  • 72,915
  • 69
  • 228
  • 366
Emre
  • 11
  • 1
  • It's interesting the way different people think differently; I think it makes more sense to check if the number of elements is zero rather than checking if the first element is present. – Sam Aug 10 '12 at 08:32
0

when the object is empty return this error:

Uncaught TypeError: Cannot read property '0' of null

I try this code :

try{
  if ($("#btext" + i).length) {};               
}catch(err){
  if ($("#btext" + i).length) {
     //working this code if the item, not NULL 
   }
}
Community
  • 1
  • 1
ahmadjn
  • 1
  • 1
-4
if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}
-7

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!

Instead try this:

if($("#something") !== null){
  // do something
}

or

if($("#something") === null){
  // don't do something
}
Wolf
  • 17
  • 1
  • 1
  • 6