简体   繁体   中英

Is there a way to compare jQuery objects while ignoring the HTML attributes' ORDER?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM