Running the following comparison by using jQuery's "is" function will return false, since the DOM elements aren't exactly the same, although visually and functionally they are the same:
var $a = $('<div id="test" href="http://www.google.com"></div>');
var $b = $('<div href="http://www.google.com" id="test"></div>');
$a.is($b);//FALSE
Using direct comparison of the DOM objects will return false as well.
See Running example: http://jsfiddle.net/6zqwn/5/
So, is there a way to avoid taking the attributes' order into account when comparing?
(Why am I asking this question: I am using these comparisons in cross-browser unit tests in which different browsers change the attributes' order while still functionally creating the same DOM elements.)
If we need to ignore the attributes' order, we can use a jQuery selector as the parameter to the "is" function, and then compare the elements' inner HTML separately.
Using the same example from the question:
var $a = $('<div id="test" href="http://www.google.com"></div>');
var $b = $('<div href="http://www.google.com" id="test"></div>');
var selector = 'div#test[href="http://www.google.com"]';
($a.is(selector) == $b.is(selector)) && ($a.html() == $b.html());//TRUE
See running example: http://jsfiddle.net/GuQ53/4/
UPDATE
An easier solution that Joe linked to in the comments, which should work in IE9+ and handle child elements as well, is using the native "isEqualNode" function. See solution here: https://stackoverflow.com/a/19342581/1785003
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