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