Asked : Nov 17
Viewed : 20 times
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?
Nov 17
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.
answered Jan 28
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 */ }
answered Jan 28
You could use this:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
answered Jan 28
Use the .length
property of the jQuery collection returned by your selector:
if ( $( "#myDiv" ).length ) {
$( "#myDiv" ).show();
}
Note that it isn't always necessary to test whether an element exists. The following code will show the element if it exists, and do nothing (with no errors) if it does not:
$( "#myDiv" ).show();
answered Jan 28
If you are someone strongly committed to using the jQuery library, you can use the .inArray( ) method.
If the function finds the value, it returns the index position of the value and -1 if it doesn't.
jQuery.inArray(search-value, array-or-string-in-which-to-search);
//code to check if a value exists in an array using jQuery
<script type = 'text/javascript' >
var fruits_arr = ['Apple', 'Mango', 'Grapes', 'Orange', 'Fig', 'Cherry'];
var text = "Watermelon";
// Searching in Array
console.log('Index : ' + jQuery.inArray('Fig', fruits_arr));
console.log('Index : ' + jQuery.inArray('Peach', fruits_arr));
// Searching in String variable
console.log('Index : ' + jQuery.inArray("m", text));
</script>
Index : 4
Index : -1
Index : 5
answered Jan 28