Saturday, February 20, 2010

Comparing two objects in jQuery

Had a strange problem in comparing two objects in js. I am dynamically creating a number of divs, adding them to the DOM and also placing them into an array in order to keep tack of what divs are hidden or shown at a given time. Later, I tried to loop through all of the divs and compare them using the === operator but they never returned true -- even though both objects were divs and even showed the same innerHTML.

Anway, a Google search turned up a suggestion to add this function to the jQuery prototype:

$.fn.equals = function(compareTo) {
if (!compareTo || !compareTo.length || this.length!=compareTo.length)
{
return false;
}
for (var i=0; i
if (this[i]!==compareTo[i]) {
return false;
}
}
return true;
}

Problem fixed!

No comments: