algorithm for alphabetical insert - special case
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)
set inserted to false
go through the list
if the current item of the list is alphabetic comes after the one to be inserted
then
insert it before
mark it as inserted ie inserted is true
If after going though the whole list (ie inserted is false) then just append it to the list
精彩评论