Wednesday, August 5, 2009

Javascript Array from getElementsByTagName is LIVE!

The array returned by getElementsByTagName() function is LIVE!

What I mean by LIVE is that as you traverse the array and invoke changes to the DOM, the items in the array itself can change automatically! Here's an example:

var inputEls = divEl.getElementsByTagName('input');
for (var j=0; j < inputEls.length; j++) {
alert('inputEls length='+inputEls.length);
var inputEl = inputEls[j];
inputEl.parentNode.removeChild(inputEl);
}

What you'll actually see is that the length of the array automatically decreases with each iteration because I am removing those elements from the DOM.

To work around this issue I had to traverse the array backwards:

for(var i=inputEls.length-1;i>=0; i--) {

}

Tuesday, August 4, 2009

Java TreeSet missing elements

If you notice that some elements may be missing after having added them to a TreeSet then it is probably because your implementation of Comparator or Comparable is incorrect.

This is the key note to remember:

"If two elements are different but compareTo returns 0, then TreeSet will consider them equal, and the newly added element replaces the old one".