js节点

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .main{width: 400px;height: 400px;border: 1px solid #000;position: relative}
        .box{width: 200px;height: 200px;background: yellowgreen;position: absolute;bottom:20px;overflow: hidden;}
    </style>
</head>
<body>
<div class="main">
    <div class="box"></div>
    <div class="box2"></div>
    <div class="box3"></div>
    <div class="box4"></div>
    <div class="box5"></div>
</div>
<script>
    var main=document.getElementsByClassName("main")[0];
    var box=document.getElementsByClassName("box")[0];
    var box2=document.getElementsByClassName("box2")[0];
    var box3=document.getElementsByClassName("box3")[0];
    var box4=document.getElementsByClassName("box4")[0];
    var box5=document.getElementsByClassName("box5")[0];

    console.log(main.childNodes);      //.获取子节点包括文本节点
    console.log(main.firstChild );     //.获取第一个子节点包括文本节点
    console.log(main.lastChild );      //.获取最后一个子节点包括文本节点
    console.log(main.parentNode);      //.获取父节点
    console.log(box.nextSibling );     //.获取下一个相邻兄弟节点包括文本节点
    console.log(box2.previousSibling); //.获取上一个相邻兄弟节点包括文本节点
    console.log(main.firstElementChild); //获取第一个子元素节点
    console.log(main.lastElementChild); //获取最后一个子元素节点
    console.log(box.nextElementSibling); //获取下一个相邻兄弟元素节点
    console.log(box2.previousElementSibling); //获取上一个相邻兄弟元素节点
    console.log(box.children); //获取所有的子元素节点,不包括孙子元素
    console.log(main.nodeValue); //nodeValue 输出节点 如果是文本节点或者注释节点,则会打印输出内容;如果是元素节点,则打印输出null;
    console.log(main.nodeName); // 输出节点名称
    console.log(main.nodeType); // 输出节点类型

    main.setAttribute("id","id");//设置属性  setattribute("属性名","属性值");
    main.removeAttribute("id");//删除属性  removeAttribute("value");

    var span=document.createElement("span");//创建节点
    document.body.appendChild(span);//插入节点;
    main.insertBefore(span,box);//将元素节点a插入到元素节点b之前insertBefore(a,b)将元素节点a插入到元素节点b之前
    main.replaceChild(box4,box3);//b节点被a节点替换,a节点消失
    main.removeChild(box5);//删除节点


</script>
</body>
</html>
原文地址:https://www.cnblogs.com/xiaobaibubai/p/8022131.html