How to Check If a Selector Matches Something in Jquery

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

As the other commenters are suggesting the most efficient way to do it seems to be:

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

If you absolutely must have an exists() function - which will be slower- you can do:

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

Then in your code you can use

if ($(selector).exists()) {
// Do something
}

As answered here

Check if given selector matches given object

You can tell if an object is a div using:

$('selector').is('div');

Or for a direct comparison:

$('selector1')[0].tagName == $('selector2')[0].tagName

jQuery - how to test if selector matches anything?

if ($('#foo').length > 0) {

// do things
}

should do it

How do I check if 2 jQuery selectors are pointing to the same element(s)?

There is nothing in the core library to check sequence equality of jQuery objects, however the following should do the trick:

$.fn.sequenceEqual = function(compareTo) {
if (!compareTo || !compareTo.length || this.length !== compareTo.length) {
return false;
}
for (var i = 0, length = this.length; i < length; i++) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
}

Which would be useable like so:

$(".foo").sequenceEqual($(".bar"))

For completeness, a contents equal method could be written like so:

$.fn.contentsEqual = function(compareTo) {
return compareTo && this.length === compareTo.length && this.length === this.filter(compareTo).length;
}

Which would be useable like so:

$(".foo").contentsEqual($(".bar"))

Checking if a jQuery selector doesn't find any results

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

Used like:

$("#notAnElement").exists();

Check if an object exists by its selector, return a boolean value with jQuery or Javascript

There is no boolean for that because it would prevent from chaining.

You could use $(something).length>0.

But if you need to run in over and over again, I made a little jQuery plugin which is called doesExist()

/* doesExist PLUGIN (c) MS */
/* (c) Michael Stadler(MS), */
(function($){
$.fn.doesExist = function()
{
return jQuery(this).length > 0;
};
})(jQuery);

The usage of it would be

if($('#something').doesExist()){
//doesExist returns a boolean
}

Check if element exists in jQuery

$('elemId').length doesn't work for
me.

You need to put # before element id:

$('#elemId').length
---^

With vanilla JavaScript, you don't need the hash (#) e.g. document.getElementById('id_here') , however when using jQuery, you do need to put hash to target elements based on id just like CSS.

What is the best way to check if a selector exists?

There's no more efficient method to let jQuery stop after finding a matching element.
It's not even possible in Vanilla ("pure") JavaScript to limit document.getElementsByTagName("p") to match only one element, without having a worse performance.



Related Topics



Leave a reply



Submit