Mhd
Mhd

Reputation: 2978

How to compare two HTML elements rendering

I'm trying to compare two sting spans.

For example, I have as input:

var span1 = "<SPAN style=\"FONT-SIZE: 9pt; FONT-FAMILY: Arial; FONT-WEIGHT: bold\">hello<FONT style=\"FONT-FAMILY: Wingdings; COLOR: #ffff00\">ll</FONT>hi<BR><BR></SPAN>";

var span2 = "<span style=\"font-weight: bold; font-size: 9pt; font-family: Arial;\">hello<font style=\"color: #FFFF00; font-family: Wingdings;\">ll</font>hi<br><br></span>"

Those two spans will render the same thing in UI. But I can't find a proper way to prove that are equals using JavaScript or JQuery.

I looked at this question, but the response does not work for me because:

Also that question is little bit old. So I thought may be there is a new that I can follow?

Upvotes: 3

Views: 1374

Answers (2)

jcaron
jcaron

Reputation: 17710

What you can do is:

  • render the elements by assigning the HTML to the innerHTML property of an existing element
  • recursively walk through the DOM for each resulting tree
  • for each element node, check the element name, and use the getComputedStyle method to compare all computed styles
  • for text nodes, just compare contents. You may have to do some cleanup (trim, replaces spaces, possibly convert to a canonical encoding...)

The details of how accurately you need to match things and how often this will work depend a lot on what you are trying to achieve exactly and the sources of the HTML, so YMMV.

There may also be options involving rendering as images and comparing the images, but afaik this is not quite straightforward in a browser (but could be if you do this server side with a headless browser).

Upvotes: 1

ryanpcmcquen
ryanpcmcquen

Reputation: 6455

In theory, you are looking for an anagram:

var span1 =
    '<SPAN style="FONT-SIZE: 9pt; FONT-FAMILY: Arial; FONT-WEIGHT: bold">hello <FONT style="FONT-FAMILY: Wingdings; COLOR: #ffff00">ll</FONT> hi<BR><BR></SPAN>';

var span2 =
    '<span style="font-weight: bold; font-size: 9pt; font-family: Arial;">hello<font style="color: #FFFF00; font-family: Wingdings;">ll</font>hi<br><br></span>';

const processForAnagram = str => str.replace(/(\s|"|'|;)/gi, '').toLowerCase().split('').sort().join('');
const isAnagram = (first, second) =>
    processForAnagram(first) === processForAnagram(second);

console.log(
    isAnagram(span1, span2)
);

This could present some red herrings, but chances are unlikely the larger the element is.

Upvotes: 0

Related Questions