Compare two HTML elements for differences
by neonDog
JavaScript
function compareDumps(bs4, bs5) {
const diffs = []
const len = Math.min(bs4.length, bs5.length)
for (let i = 0; i < len; i++) {
const el4 = bs4[i]
const el5 = bs5[i]
const identity = `${el4.tag}#${el4.id || ""}.${el4.class}`
// Compare computed styles
const styleDiffs = {}
for (const prop in el4.styles) {
const val4 = el4.styles[prop]
const val5 = el5.styles[prop]
if (val4 !== val5) {
styleDiffs[prop] = { bs4: val4, bs5: val5 }
}
}
// Compare metrics
const metricsDiffs = {}
for (const prop in el4.metrics) {
if (typeof el4.metrics[prop] === "object") {
for (const sub in el4.metrics[prop]) {
const v4 = el4.metrics[prop][sub]
const v5 = el5.metrics[prop][sub]
if (v4 !== v5) {
metricsDiffs[`${prop}.${sub}`] = { bs4: v4, bs5: v5 }
}
}
} else {
const v4 = el4.metrics[prop]
const v5 = el5.metrics[prop]
if (v4 !== v5) {
metricsDiffs[prop] = { bs4: v4, bs5: v5 }
}
}
}
if (Object.keys(styleDiffs).length || Object.keys(metricsDiffs).length) {
diffs.push({
index: i,
element: identity,
styleDiffs,
metricsDiffs,
})
}
}
console.log(`Found ${diffs.length} differing elements`)
return diffs
}