logo

Element Traversal规范中的firstElementChild、lastElementChild、previousElementSibling、nextElementSibling、childElementCount属性

作者:孟宪会 阅读:1222 发表于:2010-08-09 16:49:57

Element Traversal规范定义了ElementTraversal接口,它允许脚本遍历DOM树中的元素(element)节点,而不包含元素节点之外的其他节点,如注释节点、文字节点等。这个规范给我们提供了快速、方便的方法来访问元素节点。在以前的方法中,我们使用firstChild、nextSibling、childNodes、childrem等方法来进行遍历,但要得到元素节点,我们还需要来判断节点的类型。

注意:children属性中,IE里面包含注释节点,而其他浏览器则不包含。

ElementTraversal接口定义了5个属性,是元素节点必须要实现的,这5个属性的原始定义如下,这些属性,看名字就不难明白它的含义,再次不进行翻译成中文了:

firstElementChild:Returns the first child element node of this element. null if this element has no child elements.
lastElementChild:Returns the last child element node of this element. null if this element has no child elements.
previousElementSibling:Returns the previous sibling element node of this element. null if this element has no element sibling nodes that come before this one in the document tree.
nextElementSibling:Returns the next sibling element node of this element. null if this element has no element sibling nodes that come after this one in the document tree.
childElementCount:Returns the current number of element nodes that are children of this element. 0 if this element has no child nodes that are of nodeType 1.

现在,IE9,Firefox3.5+,Safari,Opera,Chrome浏览器都已经实现该接口。下面就是利用这些属性的一个简单的例子: 

HTML 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
</head>
<body>
<div id="container">
    这里是文字节点。
    
<br/>
    
<!-- 这里是注释文字 -->
    
<div>这个是真正的节点。</div>
    
<mxh>自定义标签被认可吗?</mxh>
</div>
<input type="button" value="点击这里进行测试" onclick="showChildNodes()" />
<script>
function showChildNodes()
{
var container = document.getElementById("container");
var out = "";
out
+= "<li>浏览器类型是:" + navigator.userAgent;
out
+= "<li>childNodes.length = " + container.childNodes.length;
out
+= "<li>children.length = " + container.children.length;
out
+= "<li>childElementCount  = " + container.childElementCount;
document.getElementById(
"debug").innerHTML = out;

var child = container.firstElementChild;
while (child) {
    alert (child.nodeName
+ ":" + child.innerHTML );
    child
= child.nextElementSibling;
}
}
</script>
<br/>
<div id="debug" style="border:1px solid red"></div>
</body>
</html>

DOM规范中定义的nodeType类型:

ELEMENT_NODE                   = 1;
ATTRIBUTE_NODE                 = 2;
TEXT_NODE                      = 3;
CDATA_SECTION_NODE             = 4;
ENTITY_REFERENCE_NODE          = 5;
ENTITY_NODE                    = 6;
PROCESSING_INSTRUCTION_NODE    = 7;
COMMENT_NODE                   = 8;
DOCUMENT_NODE                  = 9;
DOCUMENT_TYPE_NODE             = 10;
DOCUMENT_FRAGMENT_NODE         = 11;
NOTATION_NODE                  = 12;