Dom 节点

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title id="tit">node</title>
    </head>
    <body id="b">
        <!-- title的子节点为文本节点:Node
        h1和p为同胞 -->
        <h1 id="h1">Node</h1>
        <p>node</p>
        
        <div id="div1">
            <p id="p1">1</p>
            <p id="p2">2</p>
        </div>
        <script type="text/javascript" src="Dom_node.js">
            
        </script>
    </body>
</html>
//访问文本节点
    var myTitle=document.getElementById("tit").innerHTML;
    var myTitle2=document.getElementById("tit").firstChild.nodeValue;
    var myTitle3=document.getElementById("tit").childNodes[0].nodeValue;
    console.log(myTitle);
    console.log(myTitle2);
//访问完整文档
    alert(document.body.innerHTML);
    alert(document.documentElement.innerHTML);
//节点属性
var myH=document.getElementById("h1");
    //nodeName 节点名称
        //元素节点为节点名
        //属性节点属性名
        //文本节点#text
        console.log(myH.nodeName);
        console.log(myH.firstChild.nodeName);
    //nodeType 节点类型
        //元素节点 1
        //属性节点 2
        //文本节点 3
        console.log(myH.nodeType);
        console.log(myH.firstChild.nodeType);
//创建新元素
    
    //创建新div元素
    var myDiv=document.createElement("div");
    //添加到body元素中
    var myBody=document.getElementById("b");
    myBody.appendChild(myDiv);
    //向div元素写内容
    var text=document.createTextNode("new div");
    myDiv.appendChild(text);
    
//在已有文本节点的元素插入
    var newP=document.createElement("p");
    var newP_text=document.createTextNode("3");
    newP.appendChild(newP_text);
    var firstChild=document.getElementById("div1").firstChild;
    document.getElementById("div1").insertBefore(newP,firstChild);
//删除节点
    // //第一种无需知道父节点
    // var p1=document.getElementById("p1");
    // p1.parentNode.removeChild(p1);
    //第二种需要知道
    var myDiv1=document.getElementById("div1");
    myDiv1.removeChild(p1);

//替换元素
    var newText=document.createTextNode("new Text");
    
    var p2=document.getElementById("p2");
    var oldText=p2.firstChild;
    p2.replaceChild(newText,oldText);

 

posted @ 2022-03-21 19:18  lwx_R  阅读(16)  评论(0编辑  收藏  举报