Dom笔记2

来源:互联网 发布:手机噪音检测软件 编辑:程序博客网 时间:2024/05/24 04:31

1. childNodes:

在一棵节点树上,childNodes可以获取任何一个元素的所有的子元素,它是包含这个元素全部子元素的数组:

element.childNodes

那么来看下返回的这个数组到底是什么?

<divid="hello">123
    <ulid="world"title="123">
        <li>123</li>
    </ul>
</div>

var helloVar =document.getElementById("hello");
console.log(helloVar.childNodes.length);

发现返回的数组长度为3;数组详情如下:

NodeList[3]

0: text

1: ul#world

2: text

经过验证第一个和第三个text代表的是divul之间的‘1234’回车空格。

2. nodeType:

节点类型,每个节点都有nodeType属性。这个属性能够让我们了解到我们正在和那个节点打交道:

node.nodeType

console.log(helloVar.nodeType);

这个时候发现结果为1’,其实nodeType属性总共有12种可取值,但其中仅有三种具有实用使用价值。

元素节点的nodeType属性值为1

属性节点的nodeType属性值为2

文本节点的nodeType属性值为3

3. nodeValue:

如果想改变一个文本节点的值,那么这个时候可以使用Dom提供的nodeValue,可以用来获得和设置一个节点的值。

node.nodeValue

现在我们要得到li所包含的文本值

var itemLi = document.getElementsByTagName('li')[0];
console.log(itemLi.nodeValue);

返回的将是一个null,而我们需要的本来就不是<li>元素本身的nodeValue,那么我们现在要先获得这个文本节点然后再调用nodeValue.

console.log(itemLi.childNodes[0].nodeValue);

这样就得到了123

4. firstChild lastChild

上面的childNodes[0]可用firstChild替代。意义显而易见,获得childNodes的第一个元素和最后一个元素。

那么最后如果想将li里面的123改变那么这个时候只要

itemLi.childNodes[0].nodeValue="good";这样就ok了。

 

 

 

 

0 0