DOM

255 阅读7分钟

DOM

DOM就是Document Object Model(文档对象模型)的缩写,DOM 是 W3C(万维网联盟)的标准。 DOM是中立于平台和语言的接口,它允许程序和脚本动态地访问和更新文档的内容、结构和样式。

HTML-页面结构 CSS-页面样式 JavaScript-页面行为操作 image.png

获取元素

  • 通过js代码来获取元素
  • 获取到元素之后就可以进行一些相关的操作了

getElementById():

  • 获取特定ID元素的节点对象(返回一个对象)
  • 因为在一个页面中 id 是唯一的,所以获取到的就是一个元素
// document.getElementById()// 通过id获取
<body>
   <div id="box"></div>
   <script>
       var box = document.getElementById('box')
       console.log(box) // <div></div>
   </script>
</body>
  • 获取到的就是页面中的那个 id 为 box 的 div 标签

getElementsByTagName():

  • 获取指定标签名的节点列表(返回一个数组)
  • getElementsByTagName 是用过标签的 标签 名称来获取标签的
  • 因为页面中可能有多个元素的 标签 名称一样,所以获取到的是一组元素
  • 哪怕真的只有一个这个标签名,那么也是获取一组元素,只不过这一组中只有一个 DOM 元素而已
<body>
   <div></div>
   <script>
       var box = document.getElementsByTagName('div')
       console.log(box) // [<div></div>]
       console.log(box[0]) // <div></div>
   </script>
</body>
  • 和 getElementsByClassName 一样,获取到的是一个长得很像数组的元素
  • 必须要用索引才能得到准确的 DOM 元素

getElementsByName():

  • 获取相同name属性值的节点列表(返回一个数组)

  • getElementsByName 是用过标签的 name 来获取标签的

  • 因为页面中可能有多个元素的 name 一样,所以获取到的是一组元素

  • 哪怕真的只有一个这个name ,那么也是获取一组元素,只不过这一组中只有一个 DOM 元素而已

<body>
   <div></div>
   <script>
       var box = document.getElementsByName('div')
       console.log(box) // [<div></div>]
       console.log(box[0]) // <div></div>
   </script>
</body>

getElementsByClassName():

  • 获取相同的class名的节点列表(返回一个数组)
  • getElementsByClasssName 是用过标签的 class 名称来获取标签的
  • 因为页面中可能有多个元素的 class 名称一样,所以获取到的是一组元素
  • 哪怕真的只有一个这个class,那么也是获取一组元素,只不过这一组中只有一个 DOM 元素而已
<body>
   <div></div>
   <script>
       var box = document.getElementsByClassName('div')
       console.log(box) // [<div></div>]
       console.log(box[0]) // <div></div>
   </script>
</body>

querySelector():

  • 支持后代,子选择器,类,id,属性选择器....(返回一个对象)推荐
console.log(document.querySelector('div')) // 获取页面中的第一个 div 元素
console.log(docuemnt.querySelector('.box')) // 获取页面中第一个有 box 类名的元素
console.log(document.querySelector('#box')) // 获取页面中第一个 id 名为 box 的元素

querySelectorAll():

  • 支持后代,子选择器,类,id,属性选择器....(返回一个集合)推荐
console.log(document.querySelectorAll('div')) // 获取页面中的所有的 div 元素
console.log(docuemnt.querySelectorAll('.box')) // 获取页面中所有有 box 类名的元素

DOM节点的分类

DOM节点分类有三种:

元素节点,属性节点,文本节点,这些节点都有三个共同的属性,nodeName,nodeType,nodeValue image.png 注释节点:nodetype的值为8

元素节点

  • 元素节点的类型,名称,值
<div id="box" name = "obox" class="box">我是盒子</div>
<script>
var oBox = document.getElementById("box");  //返回一个dom对象
console.log(oBox.nodeType);     //类型:1
console.log(oBox.nodeName);     //名称:DIV
console.log(oBox.nodeValue);    //值:null
</script>

属性节点 attributes

  • 通过attributes获取属性节点
<div id="box" name = "obox" class="box">我是盒子</div>
<script>
var oBox = document.getElementById("box");  //返回一个dom对象
console.log(oBox.attributes[0].nodeType);   //节点类型:2
console.log(oBox.attributes[0].nodeName);   //节点名称:id
console.log(oBox.attributes[0].nodeValue);  //节点的值:box
</script>

文本节点 childNodes

  • 通过childNodes获取文本节点
<div id="box" name = "obox" class="box">我是盒子</div>
<script>
var oBox = document.getElementById("box");  //返回一个dom对象
console.log(oBox.childNodes[0].nodeType);   //类型:3
console.log(oBox.childNodes[0].nodeName);   //名称:#text
console.log(oBox.childNodes[0].nodeValue)   //值:我是盒子
</script>

属性操作

查看属性 attributes 获取当前所有的属性

<button>查看属性</button>
<button>获取属性</button>
<button>设置属性</button>
<button>移出属性</button>
<button>增加属性</button>
<img src="./image/1.jpg" alt="">
<script>
    var oBtns = document.querySelectorAll("button");
    var oImg = document.querySelector("img");

//查看属性  attributes 获取当前dom所有的属性
    oBtns[0].onclick = function(){
        console.log(oImg.attributes);
        for(var key in oImg.attributes){
            if(oImg.attributes[key].nodeType == 2){
                console.log(oImg.attributes[key]);
            }
        }
    }
</script>

获取属性 getAttributes("属性名称") 返回属性的值

oBtns[1].onclick = function(){
    var val = oImg.getAttribute("src");
    console.log( val);
}

设置属性 setAttributes("属性名称","属性的值")

oBtns[2].onclick = function(){
    oImg.setAttribute("src","./image/2.jpg");
}

删除属性 removeAttribute("属性名称")

oBtns[3].onclick = function(){
    oImg.removeAttribute("src")
}

状态属性

  • checked,selected,disabled等...
  • 不能用setAttribute,getAttribute,removeAttribute操作!(会失效)
  • 可以通过checked = true/false来设置
<button>设置</button>
<button>获取</button>
<button>取消</button>
<input type="checkbox">
<script>
    //状态属性
    //状态属性
    //    checked selected disabled ,不能用 setAttribute,getAttribute,removeAttribute操作!
    //
    var oBtns = document.querySelectorAll("button"); // HTMLButtonElement  HTMLDIVElement
    var oCbx = document.querySelector("input"); // HTMLInputElement

    //设置
    oBtns[0].onclick = function () {
        // oCbx.setAttribute("checked", "checked")
        oCbx.checked = true;
    }

    oBtns[1].onclick = function () {
        // console.log(oCbx.getAttribute("checked"));
        console.log(oCbx.checked);
    }
    oBtns[2].onclick = function () {
        // oCbx.removeAttribute("checked")
        oCbx.checked = false;
    }
    </script>

节点创建

创建元素节点

  • createElement("元素名称") 创建元素节点
var obox = document.createElement("div")  //  创建元素节点

创建属性节点

  • setAttribute("属性","值") 创建属性节点
obox.setAttribute("class","box");  //设置/创建了一个属性叫class且值为box

创建文本节点

  • createTextNode("文本内容") 创建文本节点
 var oTxt = document.createTextNode("我是动态文字");

节点的相关操作

追加节点 appendChild()

  • 父节点.appendChild(子节点)
document.body.appendChild(oDiv);
//父.appendChild(子节点)

插入节点 insertBefore()

  • 父节点.insertBefore(子节点,参照物)
  • 子节点,插入在参照物的前面
  • 参照物值为null,则往最后一个元素的后面插入
var oLis3 = document.querySelector("#li3");
var oBox = document.createElement("div");
oLis3.parentNode.insertBefore(oBox,null);

删除节点 removeChild()

  • 父节点.removeChild(子节点)
  • 父节点删除子节点
oLi3.parentNode.removeChild(oLi3);

删除自身 remove()

  • 自己.remove()
  • 自己删除自己
 oLi3.remove();

替换节点 replaceChild()

  • 父节点.replaceChild(新子节点,旧子节点)
  • 由新的节点替换旧的节点
oLi3.parentNode.replaceChild(oBox,oLi3)

克隆节点 cloneNode()

  • 浅克隆 cloneNode(false) 只能克隆自己,不能克隆子元素
  • 深克隆 cloneNode(true) 会克隆自己,也会克隆自己的子元素,但是不会克隆事件
//浅克隆    cloneNode(false)    只能克隆自己,不能克隆子元素
oBtns[0].onclick = function () {
    var oClone = oBox.cloneNode(false);//在内存中
    //把克隆的dom添加到页面中
    document.body.appendChild(oClone);
}

//深克隆   cloneNode(true) 会克隆自己,也会克隆自己的子元素,但是不会克隆事件
oBtns[1].onclick = function () {
    var oClone = oBox.cloneNode(true);//在内存中
    //把克隆的dom添加到页面中
    document.body.appendChild(oClone);
}

节点关系

父节点和子节点

  • parentNode 获取父节点
var oLis3 = document.querySelector("#li3");
oLis3.parentNode.style.backgroundColor = "green"
  • 获取所有的儿子
  • children 微软 ie 推荐,会在ie下,把注释当成元素节点
  • childNodes 文本节点+元素节点 w3c规范
// children 微软 ie 推荐,会在ie下,把注释当成元素节点
console.log(oBox.children);
for(var i=0;i<oBox.children.length;i++){
    oBox.children[i].style.backgroundColor = i%2==0 ?"yellow":"green"
}
  • 获取第一个儿子 firstELementChild 或 firstChild
  • firstChild 为ie而生,但是在google页面上也可以使用,但是返回的有可能是文本节点
  • firstElementChild 为google而生,在ie上会是null 重点
//兼容写法
var oChild = oBox.firstElementChild ||oBox.firstChild;//了解
oChild.style.backgroundColor = "yellow"
  • 获取第最后一个儿子 lastELementChild 或 lastChild
  • lastChild 为ie而生,但是在google页面上也可以使用,但是返回的有可能是文本节点
  • lastElementChild 为google而生,在ie上会是null 重点
//兼容写法
var oChild = oBox.lastElementChild ||oBox.lastChild;//了解
oChild.style.backgroundColor = "yellow"

兄弟节点

  • previousSibling: 属性返回该节点的前一个同级节点 ie
  • previousElementSibling: 属性返回该节点的前一个同级节点google
  • nextSibling: 属性返回该节点的后一个同级节点 ie
  • nextElementSibling: 属性返回该节点的后一个同级节点 google
<body>
    <ul>
        <li>我是第1个</li>
        <li>我是第2个</li>
        <li id="li3">我是第3个</li>
        <li>我是第4个</li>
        <li>我是第5个</li>
    </ul>
    <script>
        //兼容写法
        //前面一个 perviousELementSibling || previousSibling
        var oLi3 = document.querySelector("#li3");
        var oPre = oLi3.previousElementSibling || oLi3.previousSibling;
        oPre.style.backgroundColor = "yellow"
        //兼容写法
        //后面一个 nextElementSibling || nextSibling
        var oNext = oLi3.nextElementSibling || oLi3.nextSibling;
        oNext.style.backgroundColor = "green"
        
    </script>
</body>

操作类的值的方法(classList与className)

classList 和 className的区别

  • 相同:classList和className都可以增加类名,也可以删除类名
  • 不同:className会覆盖原理class的值,classList的方法更加灵活

add() 添加类名

  • 给class里面添加一个或多个类名
<style>
    .box{
        width: 200px;
        height: 200px;
        background-color: green;
    }
    .aaa{
        background-color: red;
    }
    .bbb{
        border-radius: 50%;
    }
</style>
<body>
    <button>添加</button>
    <button>移出</button>
    <button>切换</button>
    <button>替换</button>
    <div class="box">
        我是盒子
    </div>
</body>
<script>
    var oBtns =document.querySelectorAll("button");
    var oBox = document.querySelector(".box");
    //1.添加类名称
    oBtns[0].onclick = function(){
        oBox.classList.add("aaa","bbb")
    }
</script>

remove() 移出类名

  • 从class里面移出一个或多个类名
//2.移出类名称
oBtns[1].onclick = function(){
    oBox.classList.remove("aaa","bbb")
}

replace() 替换类名

  • 前一个类名替换后一个 类名
//3.替换类名称  前面参数的值 被后面一个参数给替换了
oBtns[3].onclick =function(){
    oBox.classList.replace("aaa","bbb")
}

toggle() 切换类名

  • 不存在类名就把类名添加,存在类名就把类名移除
//切换类名称
oBtns[2].onclick = function(){
    //通过contains结合remove 和 add 实现切换类名
    // if(oBox.classList.contains("aaa")){
    //     oBox.classList.remove("aaa")
    // }else{
    //     oBox.classList.add("aaa")
    // }
    
    //简单方法  推荐
     oBox.classList.toggle("aaa");
}

contains() 包含类名

  • 判断类型是否包含,包含就返回true,不包含就返回false
oBtns[3].onclick =function(){
    oBox.classList.replace("bbb","aaa")
    console.log(oBox.classList.contains("aaa")); //true
}

排他思想

  • 先把class移除所有value,再给目标class添加value
<body>
    <button>我是按钮1</button>
    <button>我是按钮2</button>
    <button>我是按钮3</button>
    <button>我是按钮4</button>
    <button>我是按钮5</button>
    <script>
        //需求:保证只有一个红色按钮,点击的时候,给当前按钮设置红色
        var oBtns = document.querySelectorAll("button");
        
        //排他思想!
        for(var i=0;i<oBtns.length;i++){
            oBtns[i].index=i;//设置值
            oBtns[i].onclick = function(){
                //鼠标点击了谁,this就是谁
                //点击后,把所有的按钮的背景颜色设置成红色
                for(var j=0;j<oBtns.length;j++){
                    oBtns[j].style.backgroundColor = ""
                }
                //再给当前的按钮,设置红色
                this.style.backgroundColor ="red"
                // alert(this.index)//取值
            }
        }
    </script>
</body>