Javascript DOM

DOM
记住每个DOM节点都有5个指针(属性):parentNode previousSibling nextSibling fistChild lastChild.DOM指针不仅可以指向元素,也可以指向文本节点。XML存在一个有争议的地方:空格。在Firefox中把空格看做是一个文本节点。所以使用这些指针不能兼容浏览器。

1、处理DOM中的空格

 cleanWhitespace( element ) {
    // If no element is provided, do the whole HTML document
    element = element || document;
    
// Use the first child as a starting point
    var cur = element.firstChild;

    // Go until there are no more child nodes
    while ( cur != null ) {

        // If the node is a text node, and it contains nothing but whitespace
    // \S 表示任何非空白字符
        if ( cur.nodeType == 3 && ! /\S/.test(cur.nodeValue) ) {
            
// Remove the text node
            element.removeChild( cur );

        // Otherwise, if it’s an element
        } else if ( cur.nodeType == 1 ) {
             
// Recurse down through the document
             cleanWhitespace( cur );
        }

        cur = cur.nextSibling; // Move through the child nodes
    }
}

节点的类型可以由检查它的nodeType属性来确定。一般使用如下3个值:

nodeType=1    匹配元素
nodeType=3    匹配文本
nodeType=9    匹配文档的根元素

2、简单的DOM遍历

 prev( elem ) {
    do {
        elem 
= elem.previousSibling;
    } 
while ( elem && elem.nodeType != 1 );
    
return elem;
}
function next( elem ) {
    
do {
        elem 
= elem.nextSibling;
    } 
while ( elem && elem.nodeType != 1 );
    
return elem;
}
function first( elem ) {
    elem 
= elem.firstChild;
    
return elem && elem.nodeType != 1 ?
        nextSibling( elem ) : elem;
}
function last( elem ) {
    elem 
= elem.lastChild;
    
return elem && elem.nodeType != 1 ?
        prevSibling( elem ) : elem;
}
function parent( elem, num ) {
    num 
= num || 1;
    
for ( var i = 0; i < num; i++ )
        
if ( elem != null ) elem = elem.parentNode;
    
return elem;
}

Related Posts

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注