获取 html 注释节点

2013-05-04 06:48

获取 html 注释节点

by dron

at 2013-05-03 22:48:59

original http://ucren.com/blog/archives/448

因 Tracker 需要移除页面的 html 注释节点,鉴于注释的复杂性,为了靠谱点,不走正则的路子了,顺手写了个获取 html 注释节点的工具函数:

var getHtmlCommentNodes = function(){
    var cn, push;
    
    cn = document.COMMENT_NODE;
    push = [].push;

    return function f( node ){
        var result, c, l, i;

        result = [];

        if( node.nodeType == cn )
            result.push( node );
        else if( c = node.childNodes, l = c.length )
            for( i = 0; i < l; i ++ )
                push.apply( result, f( c[ i ] ) );
        
        return result;
    }
}();

用法举例:

getHtmlCommentNodes( document.documentElement );