[thelist] DOM: previousSibling and LI tags

Howard Jess howard at dhitechnologies.com
Fri Jan 20 11:23:33 CST 2006


> To be on the safe side, you can sweep all empty text nodes of interest
> before navigating through the node tree.
> sample code:
> var _this=_DOMManager.prototype;
> function _DOMManager(){}
> _this.sweep=function(obj){
>         if(!obj)obj=document;
>         var children=obj.childNodes;
>         for(var j=0;j<children.length;j++){
>                 //if node is a text node and it conists of only whitespace
>                 if(children[j].nodeType==3&&/^\s*$/.test(children[j].nodeValue))
>                         children[j].parentNode.removeChild(children[j]);
>                 if(children[j])this.sweep(children[j]);
>         }

Better to go backwards through the list of childNodes, as it's "live". If
you have childNodes

    0: whitespace-text1
    1: li-1 (with its own childNodes)
    2: whitespace-text2
    3: whitespace-text3
    4: li-2
etc., then when you remove childNodes[0], all the rest move up, and you
won't even see li-1: childNodes[1] will be whitespace-text2. Remove it,
and childNodes[2] will be li-2. Instead (untested, but illustrative):

sweep = function(obj) {
    if (!obj) obj=document;
    var children=obj.childNodes;

    for (var j = children.length-1; j >= 0; j--) {
        // if node is a whitespace-only text node
        if (children[j].nodeType==3 && /^\s*$/.test(children[j].nodeValue))
        else if (children[j].hasChildNodes()) 


More information about the thelist mailing list