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;
1 Answer 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
answered Aug 28, 2011 at 17:52
Ed Heal
60.4k18 gold badges92 silver badges137 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
d.tagname=='undefined'andd.tagName.toLowerCase()==="a"...)