现在的位置: 首页 > 综合 > 正文

36-JavaScript-DOM-dom编程初解

2014年09月05日 ⁄ 综合 ⁄ 共 2081字 ⁄ 字号 评论关闭

1. Node 对象


    Node 对象是整个 DOM 的主要数据类型。
    节点对象代表文档树中的一个单独的节点。
    节点可以是元素节点、属性节点、文本节点.

    参考: http://www.w3school.com.cn/xmldom/dom_node.asp
    参考DHTML: DHTML网页制作完全手册_.chm

2. 常用属性


    ① nodeName    String  节点名称

    ② nodeValue   String  节点值

    ③ nodeType    Number  节点类型

        参考: http://www.w3school.com.cn/xmldom/dom_nodetype.asp

        

    ④ firstChild  Node    

    ⑤ lastChild   Node

    ⑥ childNodes  NodeList

    ⑦ previousSibling  Node 前一个兄弟节点

    ⑧ nextSibling      Node 后一个兄弟节点

    ⑨ ownerDocument    Document 

    ⑩ 其他
       A) textContent   设置或返回节点及其后代的文本内容。(火狐)  
       B) text          返回节点及其后代的文本(IE 独有的属性)。
       C) attributes  Map 该节点属性集对象 (Element)


示例:

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>

<script type="text/javascript">
var ground;

function showDivInfo() {
    ground = $("ground");
    // console.info(ground);
    console.info( ground.nodeName );    // DIV
    console.info( ground.nodeType );    // 1
    console.info( ground.nodeValue );   // null
    console.info( ground.textContent );
}

function showChildren() {
    ground = $("ground");
    var children = ground.childNodes;
    
    console.info( children );
    console.info( children.length );

    // 遍历子节点
    for(var i = 0; i < children.length; i++ ) {
        console.info( "nodeName: " + children[i].nodeName 
                 + "   nodeType: " + children[i].nodeType  
                 + "   nodeValue: " + children[i].nodeValue);
    }
/*
    nodeName: #text   nodeType: 3   nodeValue: ("\n ")
    nodeName: DIV     nodeType: 1   nodeValue: null
    nodeName: #text   nodeType: 3   nodeValue: ("\n ")
    nodeName: DIV     nodeType: 1   nodeValue: null
    nodeName: #text   nodeType: 3   nodeValue: ("\n ")
*/
}

function $(id) {
    return document.getElementById(id);
}    

</script>    

<style type="text/css">
 div {
    border: 1px solid black;
    background-color: gray;
    margin: 2px;
    padding: 5px;
    width: 400px;
 }    
 #ground {
    width: 500px;
 }
</style>

</head>
<body>
    
    <div id="ground">
        <div id="rabbit">a rabbit is eating carrots! </div>
        <div id="dog">a dog is eating bones !</div>
    </div>
    
    <button onclick="showDivInfo()">ground div 's base info</button> <br/>
    <button onclick="showChildren()">ground div 's children</button> <br/>

</body>

</html>

3. 常用方法    

    
    ① hasChildNodes()   Boolean  

        判断当前节点是否拥有子节点。

    ② appendChild(newchild)     Node 

        向节点的子节点列表的末尾添加新的子节点

    ③ removeChild(node)     Node

        删除(并返回)当前节点的指定子节点

    ④ replaceChild(new_node,old_node)   Node

        将某个子节点替换为另一个

    ⑤ insertBefore(newchild,refchild)   Node

        已有的子节点前插入一个新的子节点



抱歉!评论已关闭.