![]() |
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浏览器都已经实现该接口。下面就是利用这些属性的一个简单的例子:
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;