7
var selector = '#Id-value_' + index;
var exist = $(selector).exists();

I am getting error for this piece of code.
My document ready function is

$(document).ready(function() {

});

2 Answers 2

8

There is no exists() function in jQuery. But you can quickly write one:

// Add a new function to jQuery
jQuery.fn.exists = function(){ return this.length > 0; }

// Sadly, we cannot use ES6 arrow functions here. It
// would be nice if we could do this:
// jQuery.fn.exists = () => this.length > 0;

//now let's test it
if ($(selector).exists()) {
    // Do something
}

Or, just check for the .length property not being equal to 0:

if ($(selector).length) {
  // will go here if at least one node matched
}
3

Based on @K48 answer, you could also directly check if it exists by using $(selector).length.

var selector = '#Id-value_' + index;
if ($(selector).length) {
    // Do something
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.