[javascript] How to check null objects in jQuery

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?

This question is related to javascript jquery dom object null

The answer is


if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}

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


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
}

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() ) {...}                   

(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.


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]


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

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);
}

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 
   }
}

Using the length property you can do this.

jQuery.fn.exists = function(){return ($(this).length < 0);}
if ($(selector).exists()) { 
   //do somthing
}

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() ) {...}                   

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);
}

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.

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);
}

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

What about using "undefined"?

if (value != undefined){ // do stuff } 

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

(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.


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]


if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}

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
}

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);
}

Using the length property you can do this.

jQuery.fn.exists = function(){return ($(this).length < 0);}
if ($(selector).exists()) { 
   //do somthing
}

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]


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.

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]


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


What about using "undefined"?

if (value != undefined){ // do stuff } 

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"