Post by Schubaltz on Jun 13, 2007 9:17:52 GMT -5
This is pretty much the heart of a few of my snippets. You can apply it to any object, not just nodes. Keep in mind though that it doesn't discriminate datatypes. It'll look at 2 != "2" and return false. Just change the operation to fix this.
Description: Compares the properties of two objects; returning true when all properties of comparison Object match those of reference Object. Be wary, though, not to include large objects (such as document.documentElement) in your comparison Object as these can easily halt execution over too much recursion.
Syntax: correlate(reference Object, comparison Object)
function correlate(a, b) {
for(var x in b) {
if(!a[x] && !b[x])
continue;
if(!a[x] && b[x] || a[x] && !b[x])
return false;
else if(a[x] && typeof b[x] == "object") {
if(!correlate(a[x], b[x]))
return false;
} else if(b[x].constructor == RegExp ? !a[x].match(b[x]) : a[x].toString() != b[x].toString())
return false;
}
return true;
}
Example:
<html>
<head></head>
<body><div style="width: 74%; height: 50px"><span>Hello World</span></div>
<script type="text/javascript">
<!--
var i = [ [ "I", "K" ], document.body ]
correlate(i, {
0: [ "I" ],
1: {
nodeName: "BODY",
firstChild: {
nodeName: "DIV",
style: { width: "74%", height: "50px" },
firstChild: { childNodes: { 0: { data: "Hello World" } } }
}
}
}) // true
correlate(i, { 1: { parentNode: document.documentElement } } )
// too much recursion
// script attempts evaluating page's whole node tree and the properties of each individual node
//-->
</script>
</body>
</html>
Description: Compares the properties of two objects; returning true when all properties of comparison Object match those of reference Object. Be wary, though, not to include large objects (such as document.documentElement) in your comparison Object as these can easily halt execution over too much recursion.
Syntax: correlate(reference Object, comparison Object)
function correlate(a, b) {
for(var x in b) {
if(!a[x] && !b[x])
continue;
if(!a[x] && b[x] || a[x] && !b[x])
return false;
else if(a[x] && typeof b[x] == "object") {
if(!correlate(a[x], b[x]))
return false;
} else if(b[x].constructor == RegExp ? !a[x].match(b[x]) : a[x].toString() != b[x].toString())
return false;
}
return true;
}
Example:
<html>
<head></head>
<body><div style="width: 74%; height: 50px"><span>Hello World</span></div>
<script type="text/javascript">
<!--
var i = [ [ "I", "K" ], document.body ]
correlate(i, {
0: [ "I" ],
1: {
nodeName: "BODY",
firstChild: {
nodeName: "DIV",
style: { width: "74%", height: "50px" },
firstChild: { childNodes: { 0: { data: "Hello World" } } }
}
}
}) // true
correlate(i, { 1: { parentNode: document.documentElement } } )
// too much recursion
// script attempts evaluating page's whole node tree and the properties of each individual node
//-->
</script>
</body>
</html>