节点的类型与区分

2017-05-30  本文已影响0人  hyperRect

DOM 由 NODE构成, node包含以下12种类型。

最常见的几种

Element Type: 元素节点, nodeType =1. html或xml元素。

Element 的parentNode 可以是 Document 和 Element. 

NodeValue = null.

NodeType 为当前element的 html tag名

ChildNodes 子节点可以是Element, Text, Comment, ProcessingInstruction, CDATASection 或 EntityReference.(注意没有attribute node)

常用操作方法:

创建attribute: 

document.createAttribute("attr1");

attr1.value = "anything"

element.setAttribute(attr1);

操作attribute : GetAttribute, SetAttribute. 少用 element.attr1 = "anything" 这种方式 因为不一定支持。

以及IE6低版本不支持的 removeAttribute("class")

遍历attribute: element.attributes , 支持索引器。 attributes["id"], attributes.item(number)可以返回位于number位置的attribute属性。

创建元素: document.createElement("tagtype") . tagtype指的是html的tag 名。不区分大小写。 xhtml/xml中区分。

在内存中创建后需要用element.appendChild()方法去添加进来。

注意创建元素时 IE7及更早版本需要特殊对待。


另:子节点的问题

例: <div>

                <h1>hi </h1>

        </div>

IE 忽略空text type node

其他浏览器 良好的结构 会产生空格 也就成了一个值为""的text type node.

所以在判断时要注意补充nodeType的判断句,(if nodeType == 1)


Text Type: 文本节点。nodeType = 3

nodeName  = "#text"

nodeValue 为包含的文本。

parentNode 一定是一个Element Type Node。

没有子节点。

常用操作:

创建文本节点: document.createTextNode(“text”); 再去append到一个元素节点element上。

创建多个文本节点到某个元素上 需要再用element.normalize()来合并多个文本节点 否则会混乱。相反作用的方法是element.splitText(startPos); 从startPos截后面的字符串 , 将element的text节点分成两部分。

改变值:textNode.nodeValue = "new value";


Attribute Type: 属性节点。nodeType = 2

nodeName 是attribute的名字

nodeValue 是该attribute的值

parentNode = null

HTML中没有子节点 childNodes, XML中有。

常见操作方法: 参加ELEMENT元素中部分。


Document Type: nodeType = 9. 

在html的页面中,document type只有一种应用就是document这个实例, 同时我们可以通过window.document这个方式去访问。 

注意

1.Document Node 不存在parentNode 所以值为null。 子节点可能是DocumentType , Element, ProcessingInstruction或 Comment.

通常<html>元素就是document的子节点中的第0个节点。 即document.childNodes[0]. 也可以通过内置访问方式: document.documentElement来访问这个element节点。

2.<!docType>这个是document第二种可能的子节点。

理想的访问方式是document.doctype 但这个方式在IE8以下(含)不支持, 返回的都是null

3. 第三种可能的子节点是comment类型的。问题是各浏览器的支持力度不统一。 现实意义不大。

<!-- first comment -->

<html>

<body>

</body>

</html>

<!-- second comment -->

上一篇 下一篇

猜你喜欢

热点阅读