0

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;
asked Aug 28, 2011 at 17:43
2
  • It would be helpful to see the function in which this code exists, and any other related code. The two conditions could use some explaining (i.e. d.tagname=='undefined' and d.tagName.toLowerCase()==="a"...) Commented Aug 28, 2011 at 17:49
  • Bascially, my loop fails as it loops past the last element, I can use typeof to catch this. MDN Document developer.mozilla.org/en/JavaScript/Reference/Operators/Special/… Commented Aug 28, 2011 at 17:52

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.