5

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.)

BlueYoshi
  • 1,534
  • 12
  • 18
  • 2
    I've had a look around and this seems to be an easier solution: http://stackoverflow.com/a/19342581/2287470 - e.g. `$a.get(0).isEqualNode($b.get(0))` or `$a[0].isEqualNode($b[0])`. Fiddle: http://jsfiddle.net/6zqwn/7/ - the only issue you might run into is the only IE versions it supports are 9+ (http://www.quirksmode.org/dom/core/mobile.html#t135 & http://www.quirksmode.org/dom/core/#t135) – Joe May 20 '14 at 15:15
  • We are using divs because of a specific edge case with a client that uses a "hybrid" mobile app (native code that wraps a webview) that doesn't support anchor tags correctly. – BlueYoshi May 20 '14 at 15:18
  • 2
    @Joe you can find some shims to handle IE8, e.g: http://code.ohloh.net/file?fid=lwx59vNbUCh82xE58-VCYaA49Ic&cid=ezeK_iHzygY&s=&fp=69576&mp&projSelected=true#L0 That's said, your comment should be an answer ;) – A. Wolff May 20 '14 at 15:23
  • @A.Wolff - thanks but it's all Keen's work from the answer I linked to, I just fit it to this question :) Nice that there's a shim as well! – Joe May 20 '14 at 15:25

1 Answers1

5

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

Community
  • 1
  • 1
BlueYoshi
  • 1,534
  • 12
  • 18