The DOM insertBefore method

Just a short snippet on this method:

function addDirectorySeparator() {

    
    var li = document.getElementsByTagName('li');
    var i;
    
    for(i=0; i<li.length; i++) {
    
          if(li[i].firstChild.nodeName == 'KBD') {
    
           var separatorContent = '-';
           var separator = document.createElement('span');
           separator.className = 'dir-sep';
           
           separator.appendChild(document.createTextNode(separatorContent));
    
           var item = li[i]
           var kbd = item.getElementsByTagName('kbd')[0];
           if(navigator.userAgent.indexOf('MSIE') == -1) {
               item.insertBefore(separator, kbd);
           } else {
 
 var itemHTML = item.innerHTML;
 item.innerHTML = '<span class="dir-sep">-</span>' + itemHTML;
 
           }
    
    
        }
    
    
    }

insertBefore() has the following syntax: parentElement.insertBefore(newElement, referenceElement). You need a reference element to properly add the new element within the parent node. Of course Internet Explorer has some problems with this method, so I cut it straight and I wrote a subroutine just for it.

Leave a Reply

Note: Only a member of this blog may post a comment.