I was getting an error of d.tagName is undefined in the code below. This would happen when I inserted a new element into a list in alphabetical order and it was greater then the last element in the list. In this case it should be inserted at the end of the list. e and b are the elements to be inserted and d is the element they are to be inserted before in order to maintain alphabetical order. It works fine except for the case I mentioned where the elements are the last in the list.
while(d=d.nextSibling)
{
if(d.tagName=="undefined")
{
a.insertBefore(e,d);
a.insertBefore(b,d);
break;
}
else if(d.tagName.toLowerCase()==="a" && (b.innerHTML<d.innerHTML))
{
d=d.previousSibling;
a.insertBefore(e,d);
a.insertBefore(b,d);
break;
}
}
return 1;
Algorithm is thus (is pseudo code)