If I try something such as this:
$(".foo") === $(".foo") // = false
... I get false. If I instead try this query,
$(".foo").get(0) === $(".foo").get(0) // = true
... I get true.
That's because:
{a:myObject} !== {a:myObject};
[myObject] !== [myObject];
myObject === myObject;
I'm wondering if there is any succinct way to test for this equality, preferably built into jQuery. The 2nd method I wrote only works correctly if there is at most one element which matches .foo
. The solution should work for any amount of elements.
Obviously I don't want to just check ".foo" === ".foo"
since the actual selections I'm using are more complicated. I just simplified them for this example. (E.g. I may want to check that $(this)
is selecting the same thing as $(".foo")
.)
Two different elements have similar chemical properties when they have the same number of valence electrons in their outermost energy level. Elements in the same column of the Periodic Table have similar chemical properties.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
I think you are looking for $().is
. Docs here.
var foo, bar;
foo = $('foo');
bar = $('.bar');
// This will check to see foo and bar contain the same elements
foo.is(bar); // true | false
Edit: @lolwut provided a jsfiddle for this answer. After reading the comments, I updated it and determined that this answer isn't reliable for the OP's case.
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"))
If you want to check whether both sets contain exactly the same elements (possibly in a different order), then Array#every
in combination with $.fn.index
could do the job:
var $this = $("p"),
$other = $("p");
// same length and $other contains each element of $this
var equal = $this.length === $other.length
&& Array.prototype.every.call($this, function(elem) {
return $other.index(elem) > -1;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With