0

How can I check that two jQuery objects have equivalent features, that is the same tag names, attributes, values, and text contents?

This question is not a duplicate (content-wise or identity-wise) of any of these:

Most of these apply to selected not synthesized elements, and are answered like so: compare DOM objects using [0] or .get(0); or after jQuery 1.6 use .is(). By the way, what's up with all that duplication? Anyway those methods don't work for this purpose. Example:

var xx = $('<a>', {href: '#'}).append($('<b>').text('foo'));
var yy = $('<a>', {href: '#'}).append($('<b>').text('foo'));
var zz = $('<a>', {href: '#'}).append($('<b>').text('foobar'));

I want a function, call it same_contents(), that would work like this:

> same_contents(xx, yy)
true
> same_contents(xx, zz)
false

But none of the easy or classic ways do this because they're ultimately comparing identity not contents:

> xx == yy
false
> xx == zz
false

> xx[0] == yy[0]
false
> xx[0] == zz[0]
false

> xx.is(yy)
false
> xx.is(zz)
false

My purpose for this comparison is to check that a complex object tree was resynthesized accurately using two different methods, via brute force versus via less repetitive function calls.

Bob Stein
  • 16,271
  • 10
  • 88
  • 101

1 Answers1

0

Generate and compare raw HTML.

function same_contents($x, $y) {
    return $x[0].outerHTML == $y[0].outerHTML;
}

Then:

> same_contents(xx, yy)
true
> same_contents(xx, zz)
false

Beware false-negatives for dumb reasons:

> same_contents($('<a>', {href: '#', title: 'x'}), $('<a>', {href: '#', title: 'x'}))
true
> same_contents($('<a>', {href: '#', title: 'x'}), $('<a>', {title: 'x', href: '#'}))
false

If that's a problem, maybe a normalizer would help.

Bob Stein
  • 16,271
  • 10
  • 88
  • 101
  • 1
    I wonder if innerHTML would be better as the method is same_contents, which could possibly indicate the desire to only compare the contents, rather than also comparing the top most parents as well. – Taplar May 23 '17 at 16:59