[javascript] How do you check if a selector matches something in jQuery?

In Mootools, I'd just run if ($('target')) { ... }. Does if ($('#target')) { ... } in jQuery work the same way?

This question is related to javascript jquery jquery-selectors

The answer is


firstly create a function:

$.fn.is_exists = function(){ return document.getElementById(selector) }

then

if($(selector).is_exists()){ ... }

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}

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

jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};

Alternatively:

if( jQuery('#elem').get(0) ) {}

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}

Yet another way:

$('#elem').each(function(){
  // do stuff
});

Alternatively:

if( jQuery('#elem').get(0) ) {}

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

jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};

For me .exists doesn't work, so I use the index :

if ($("#elem").index() ! = -1) {}

Yet another way:

$('#elem').each(function(){
  // do stuff
});

firstly create a function:

$.fn.is_exists = function(){ return document.getElementById(selector) }

then

if($(selector).is_exists()){ ... }

I think most of the people replying here didn't quite understand the question, or else I might be mistaken.

The question is "how to check whether or not a selector exists in jQuery."

Most people have taken this for "how to check whether an element exists in the DOM using jQuery." Hardly interchangeable.

jQuery allows you to create custom selectors, but see here what happens when you try to use on e before initializing it;

$(':YEAH');
"Syntax error, unrecognized expression: YEAH"

After running into this, I realized it was simply a matter of checking

if ($.expr[':']['YEAH']) {
    // Query for your :YEAH selector with ease of mind.
}

Cheers.


Alternatively:

if( jQuery('#elem').get(0) ) {}

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

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}

I prefer the

    if (jQuery("#anyElement").is("*")){...}

Which basically checks if this elements is a kind of "*" (any element). Just a cleaner syntax and the "is" makes more sense inside an "if"


For me .exists doesn't work, so I use the index :

if ($("#elem").index() ! = -1) {}

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

if ($('#elem')[0]) {
  // do stuff
}

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}

if ($('#elem')[0]) {
  // do stuff
}

I think most of the people replying here didn't quite understand the question, or else I might be mistaken.

The question is "how to check whether or not a selector exists in jQuery."

Most people have taken this for "how to check whether an element exists in the DOM using jQuery." Hardly interchangeable.

jQuery allows you to create custom selectors, but see here what happens when you try to use on e before initializing it;

$(':YEAH');
"Syntax error, unrecognized expression: YEAH"

After running into this, I realized it was simply a matter of checking

if ($.expr[':']['YEAH']) {
    // Query for your :YEAH selector with ease of mind.
}

Cheers.


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 jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value