节点属性

节点属性

在文档对象模型 (DOM) 中,每个节点都是一个对象。DOM 节点有三个重要的属性 :

1. nodeName : 节点的名称

2. nodeValue :节点的值

3. nodeType :节点的类型

一、nodeName 属性: 节点的名称,是只读的。

1. 元素节点的 nodeName 与标签名相同
2. 属性节点的 nodeName 是属性的名称
3. 文本节点的 nodeName 永远是 #text
4. 文档节点的 nodeName 永远是 #document

二、nodeValue 属性:节点的值

1. 元素节点的 nodeValue 是 undefined 或 null
2. 文本节点的 nodeValue 是文本自身
3. 属性节点的 nodeValue 是属性的值

三、nodeType 属性: 节点的类型,是只读的。以下常用的几种结点类型:

元素类型    节点类型
  元素          1
  属性          2
  文本          3
  注释          8
  文档          9

 访问子结点的第一和最后项

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
</head>
<body>
<div id="con">
    <p>javascript</p>
    <div>jQuery</div>
    <h5>PHP</h5>
</div>
<script type="text/javascript">
    var x=document.getElementById("con");
    document.write(x.firstChild.nodeName+" "+x.firstChild.nodeValue+" "+x.firstChild.nodeType+"<br />");
    document.write(x.lastChild.nodeName+" "+x.lastChild.nodeValue+" "+x.lastChild.nodeType+"<br />");
</script>
</body>
</html>

访问父节点parentNode

获取指定节点的父节点

语法:

elementNode.parentNode

注意:父节点只能有一个。

访问兄弟节点

 ===

插入节点appendChild()

在指定节点的最后一个子节点列表之后添加一个新的子节点。

语法:

appendChild(newnode)

参数:

newnode:指定追加的节点。

我们来看看,div标签内创建一个新的 P 标签,代码如下:

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>nextSibling</title>
</head>
<body>
<div id="oDiv">
    <p id="x">fds</p>
    <p>www</p>
</div>
<script type="text/javascript">
    var oDiv = document.getElementById("oDiv");
    var newnode = document.createElement("p");
    newnode.innerHTML = "aaaaa";
    oDiv.appendChild(newnode)
</script>
</body>
</html>

插入节点insertBefore()

insertBefore() 方法可在已有的子节点前插入一个新的子节点。

语法:

insertBefore(newnode,node);

参数:

newnode: 要插入的新节点。

node: 指定此节点前插入节点。

 

posted @ 2015-06-19 16:36  328201736  阅读(176)  评论(0编辑  收藏  举报