Is there an "exists" function for jQuery?

Viewed 842934

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}

Is there a more elegant way to approach this? Perhaps a plugin or a function?

47 Answers

In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:

if ($(selector).length)

You don't need that >0 part.

If you used

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

you would imply that chaining was possible when it is not.

This would be better:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

Alternatively, from the FAQ:

if ( $('#myDiv').length ) { /* Do something */ }

You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.

if ( $('#myDiv')[0] ) { /* Do something */ }

You can use:

if ($(selector).is('*')) {
  // Do something
}

A little more elegant, perhaps.

I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..

// Checks if an object exists.
// Usage:
//
//     $(selector).exists()
//
// Or:
// 
//     $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
};

Try this.

simple and short and usable in the whole project:

jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin

Usage:

console.log($("element-selector").exists());

_________________________________

OR EVEN SHORTER: (for when you don't want to define a jQuery plugin):

if(!!$("elem-selector")[0]) ...;

or even

if($("elem-selector")[0]) ...;
if ( $('#myDiv').size() > 0 ) { //do something }

size() counts the number of elements returned by the selector

A simple utility function for both id and class selector.

function exist(IdOrClassName, IsId) {
  var elementExit = false;
  if (IsId) {
    elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
  } else {
    elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
  }
  return elementExit;
}

calling this function like bellow

$(document).ready(function() {
  $("#btnCheck").click(function() {
    //address is the id so IsId is true. if address is class then need to set IsId false
    if (exist("address", true)) {
      alert("exist");
    } else {
      alert("not exist");
    }
  });
});

Just check the length of the selector, if it more than 0 then it's return true otherwise false.

For ID:

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}

For Class:

 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

For Dropdown:

if( $('#selector option').size() ) {   // use this if you are using dropdown size to check

   // it exists
}

I am using this:

 if($("#element").length > 0){
   //the element exists in the page, you can do the rest....
 }

Its very simple and easy to find an element.

By default - No.

There's the length property that is commonly used for the same result in the following way:

if ($(selector).length)

Here, 'selector' is to be replaced by the actual selector you are interested to find if it exists or not. If it does exist, the length property will output an integer more than 0 and hence the if statement will become true and hence execute the if block. If it doesn't, it will output the integer '0' and hence the if block won't get executed.

In Javascript

if (typeof selector != "undefined") {
   console.log("selector exists");
} else {
   console.log("selector does not exists");
}

In jQuery

if($('selector').length){
    alert("selector exists");
} else{
    alert("selector does not exists");
}

I found that this is the most jQuery way, IMHO. Extending the default function is easy and can be done in a global extension file.

$.fn.exist = function(){
  return !!this.length;
};

console.log($("#yes").exist())

console.log($("#no").exist())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="yes">id = yes</div>

With jQuery you do not need >0, this is all you need:

if ($(selector).length)

With vanilla JS, you can do the same with:

if(document.querySelector(selector))

If you want to turn it into a function that returns bool:

const exists = selector => !!document.querySelector(selector);

if(exists(selector)){
  // some code
}

There is an oddity known as short circuit conditioning. Not many are making this feature known so allow me to explain! <3

//you can check if it isnt defined or if its falsy by using OR
console.log( $(selector) || 'this value doesnt exist' )

//or run the selector if its true, and ONLY true
console.log( $(selector) && 'this selector is defined, now lemme do somethin!' )

//sometimes I do the following, and see how similar it is to SWITCH
console.log(
({  //return something only if its in the method name
    'string':'THIS is a string',
    'function':'THIS is a function',
    'number':'THIS is a number',
    'boolean':'THIS is a boolean'
})[typeof $(selector)]||
//skips to this value if object above is undefined
'typeof THIS is not defined in your search')

The last bit allows me to see what kind of input my typeof has, and runs in that list. If there is a value outside of my list, I use the OR (||) operator to skip and nullify. This has the same performance as a Switch Case and is considered somewhat concise. Test Performance of the conditionals and uses of logical operators.

Side note: The Object-Function kinda has to be rewritten >.<' But this test I built was made to look into concise and expressive conditioning.

Resources: Logical AND (with short circuit evaluation)

Thanks for sharing this question. First of all, there are multiple ways to check it. If you want to check whether an HTML element exists in DOM. To do so you can try the following ways.

  1. Using Id selector: In DOM to select element by id, you should provide the name of the id starting with the prefix (#). You have to make sure that each Html element in the DOM must have unique id.
  2. Using class selector: You can select all elements with belonging to a specific class by using the prefix (.).

Now if you want to check if the element exist or not in DOM you can check it using the following code.

if($("#myId").length){
   //id selector
} 

if($(".myClass").length){
   //class selector
} 

If you want to check any variable is undefined or not. You can check it using the following code.

let x
if(x)
  console.log("X");
else
  console.log("X is not defined");

The input won't have a value if it doesn't exist. Try this...

if($(selector).val())

No, there is no such a method. But you can extend jQuery for your own one. Current way (2022) to do that is:

jQuery.fn.extend({
  exists() { return !!this.length }
});

Use querySelectorAll with forEach, no need for if and extra assignment:

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

as the opposite to:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}
Related