Is there a way to compare jQuery objects ignoring the attributes of the ORDER HTML code?

Performing the following comparison using the jQuery "is" function will return false since the DOM elements are not 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 DOM objects will also return false.

See an example run: http://jsfiddle.net/6zqwn/5/

So, is there a way to avoid taking attribute order into account when comparing?

(Why I ask this question: I use these comparisons in cross-browser unit tests, in which different browsers reorder the attributes, while still functionally creating the same DOM elements.)

+4
source share
1 answer

If we need to ignore the attribute , we can use the jQuery selector as a parameter of the "is" function, and then separately compare the internal HTML code of the elements.

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 an example of work: http://jsfiddle.net/GuQ53/4/


UPDATE

The easier solution that Joe has to do with comments, which should work in IE9 + and handle child elements, also uses the isEqualNode built-in function.See Solution here: fooobar.com/questions/123468 / ...

+5
source

Source: https://habr.com/ru/post/1541291/


All Articles