DOM文档对象模型

10.DOM文档对象模型

1.DOM节点的组成

元素节点 属性节点 文本节点

标签就是元素节点

class id的值 等 就是属性节点

文字,空格,换行就是文本节点

 <div class="box">你好</div>
 <元素节点 属性节点>文本不节点</元素节点>

2如何获取页面元素

  1. 根据id获取getElementById

    <div id="time">2023-08-01</div>
        <script>
            // 1.因为我们从文档页面从上往下加载,所以得先有标签,所以我们script写到标签下面
            // 2.get 获得element 元素 by 通过 
            // 3.参数id是大小写敏感的字符串
            // 4.返回的是一个元素对象
            var timer = document.getElementById('time');
            console.log(timer);
            console.log(typeof timer);
            // 5.   console.dir(timer)打印我们返回的元素对象 更好的查看里面的属性和方法
            console.dir(timer)
        </script>
    
  2. 根据标签名获取

    使用getElementByTagName()方法返回带有指定标签名的对象的集合

    注意:

    1. 因为得到的是一个对象的集合,所以我们想要操作里面的元素就需要遍历
    2. 得到元素对象是动态的
     <ul>
            <li>2</li>
            <li>2</li>
            <li>2</li>
            <li>2</li>
            <li>2</li>
        </ul>
        <script>
            // 1.返回的是 获取过来元素对象的集合 以伪数组的形式存储的(只有length 下标这边属性 其他的push那些是没有的)
            var lis = document.getElementsByTagName('li');
            console.log(lis);
            console.log(lis[0]);
            // 2.我们想要依次打印里面的元素对象我们可以采取遍历的方式
            for (let i = 0; i < lis.length; i++) {
                console.log(lis[i]);
                // 3.如果页面中只有一个li,返回的还是这个伪数组的形式
                // 4.如果页面中没有这个元素,返回的是空的伪数组形式
    
            }
        </script>
    
  3. 通过HTML5新增的方法获取

    1. document.getElementByClassName(‘类名’);//根据类名返回元素对象的集合

      // 通过document.getElementsByClassName根据类名获取某些元素的集合
              var boxs = document.getElementsByClassName('box');
              console.log(boxs); //HTMLCollection(2) [div.box, div.box]
      
    2. document.querySelector(‘选择器’)//返回指定选择器第一元素对象,切记里面的选择器是需要加符号的 .box #nav 等

       // querySelector返回指定选择器的第一个元素对象
              var firstBox = document.querySelector('.box');
              console.log(firstBox);
              var nav = document.querySelector('#nav');
              console.log(nav); //div#nav
      
    3. document.querySelectorAll(‘选择器’)//根据指定选择器返回

       // querySelectorAll ()返回指定选择器所有元素对象的集合
              var allBox = document.querySelectorAll('.box');
              console.log(allBox);
              var lis = document.querySelectorAll('li');
              console.log(lis);
      
           var oList = document.querySelectorAll(".cls")//NodeList
              oList.forEach(function (item) {
                  item.style.backgroundColor = "yellow"
              })
      

      4.通过document.getElementsByName()的name属性获取

      var myName = document.getElementsByName("myName");
                 for (var i = 0; i < myName.length; i++) {
                     myName[i].style.backgroundColor = "yellow"
                 }
      
  4. 特殊元素获取

    1. 获取body元素

      document.body //返回body元素对象

    2. 获取html对象

      document.documentElement //返回html元素对象

3节点的分类

  1. 元素节点(1):box.nodeType
  2. 属性节点(2)box.attributes[0].nodeType
  3. 文本节点(3)box.childNodes[0].nodeType
  4. 注释节点(8)box.childNodes

nodeType:检查节点类型

nodeName:获取节点名称,获取到是大写的,比如DIV,SPAN…

nodeValue:获取节点的值

 var box = document.querySelector(".box")
        console.log(box.comment);
        console.dir(box)//打印一个对象
        // 元素节点
        console.log(box.nodeType);//1
        //元素节点的名称
        console.log(box.nodeName);//DIV
        // 元素节点的值
        console.log(box.nodeValue);//null
        // 属性节点 
        console.log(box.attributes[0].nodeType);//2
        // 属性名称
        console.log(box.attributes[0].nodeName);//class
        // 属性的值
        console.log(box.attributes[0].nodeValue);//box
        console.log(box.attributes[1].nodeName);//id
        console.log(box.attributes[1].nodeValue);//id
        console.log(box.attributes[2].nodeName);//style
        console.log(box.attributes[2].nodeValue);//style
        // 文本节点
        console.log(box.childNodes[0].nodeType);//3
        // 文本节点名称
        console.log(box.childNodes[0].nodeName);//#text
        // 文本节点的值
        console.log(box.childNodes[0].nodeValue);//我是盒子
        // 注释节点
        console.log(box.childNodes);
        console.log(box.childNodes[1].nodeType);
        console.log(box.childNodes[1].nodeName);
        console.log(box.childNodes[1].nodeValue);

4属性的操作

  1. 查看属性 attribute获取当前dom的所有属性
  2. 获取属性 getAttribute(“属性的名称”) 返回属性的值
  3. 设置属性setAttribute(“属性名称”,“属性的值”)
  4. 移出属性removeAttribute(“要移除的属性”)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* img {
            width: 200px;
            height: 200px;
        } */
    </style>
</head>

<body>
    <button>查看属性</button>
    <button>获取属性</button>
    <button>设置属性</button>
    <button>移除属性</button>
    <img src="./1.jpg" alt="">

    <script>
        // 1.获取所有的按钮
        var btn = document.querySelectorAll("button");
        var img = document.querySelector("img")
        // 2.查看属性 attributes 获取当前dom的所有的属性
        btn[0].onclick = function () {
            console.log(img.attributes);
            // for(var i=0;i<img.attributes.length;i++){
            //     console.log(img.attributes[i]);
            // }
            for (var key in img.attributes) {
                if (img.attributes[key].nodeType == 2) {
                    console.log(img.attributes[key]);
                }
            }
        }
        // 获取属性 getAttribute("属性的名称") 返回属性的值
        btn[1].onclick = function () {
            console.log(img.getAttribute("src"));
        }
        // 设置属性 setAttribute("属性名称","属性的值")
        btn[2].onclick = function () {
            img.setAttribute("src", "./web1.png")
        }
        // 移除属性
        btn[3].onclick = function () {
            img.removeAttribute("src")
        }
    </script>
</body>

</html>

5状态属性

checked selected disabled …,不能用setAttribute ,getAttribute ,removeAttribute等操作

6节点的创建

步骤:1.创建节点 2.添加到指点的地方

1.创建节点

createElement(“元素名称”) 创建元素节点

createTextNode(“文本内容”)创建文本内容节点

div.appendChild(txt)追加txt子节点到div上面

className 添加类名称

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            background-color: pink;
            text-align: center;
            line-height: 200px;
        }
    </style>
</head>

<body>
    <button>创建节点</button>
    <script>
        /* 
            createElement("元素名称") 创建元素节点
            createTextNode("文本内 容") 创建文本节点
            appendChild(txt) 追加子节点
            className 添加类名称
        */
        // 1.获取dom
        var btn = document.querySelector("button");
        btn.onclick = function () {
            // 2.创建节点
            var div = document.createElement("div");
            //3.添加行内样式1
            div.style.height = "200px";
            div.style.width = "200px";
            div.style.borderRadius = "50%";
            // 4.添加类样式2
            div.className = "box";//不需要带点(.).box就是box
            // 5.设置文字
            var txt = document.createTextNode("我是动态创建的文字");
            // 6.把文字追加到div里面
            div.appendChild(txt);
            // 7.把div添加到页面上
            document.body.appendChild(div);
        }


    </script>
</body>

</html>

7节点的关系

有父子关系,兄弟关系

父子节点children,parentNode
  • parentNode 获取节点 亲爹

  • firstChild 为IE而生,但是他在Google也是可以使用,但是返回的有可能是文本节点

  • firstElementChild 为Google诞生,在IE会是null 重点

  • lastChild

  • lastElementChild

  • childNode 文本节点+元素节点 w3c

  • children 元素节点 微软的ie 推荐使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="box">
        <li>我是第1li</li>
        <li>我是第2li</li>
        <li id="li3">我是第3li</li>
        <li>我是第4li</li>
        <li>我是第5li</li>
    </div>
    <script>
        // 节点关系 父 子 兄弟
        // parentNode 获取节点 亲爹
        // firstChild 为IE而生,但是他在Google也是可以使用,但是返回的有可能是文本节点
        // firstElementChild 为Google诞生,在IE会是null 重点
        // lastChild
        // lastElementChild
        // childNode 文本节点+元素节点 w3c
        // children 元素节点 微软的ie 推荐使用
        var li3 = document.querySelector("#li3");
        // 给父节点添加背景色位pink
        li3.parentNode.style.backgroundColor = "pink";
        var box = document.querySelector(".box")
        // 
        // 1.前面的儿子
        console.log(box.firstChild);//#text
        console.log(box.firstElementChild);//在IE下,firstElementChild返回的是null
        // 兼容写法
        var oChild = box.firstElementChild || box.firstChild
        oChild.style.backgroundColor = "red"
        // 2.后面的儿子
        var oLast = box.lastElementChild || box.lastChild
        oLast.style.backgroundColor = "yellow"
        // 所有的儿子们
        var oList = []
        var oChilds = box.childNodes;//w3c规范
        for (var i = 0; i < oChilds.length; i++) {
            if (oChilds[i].nodeType == 1) {
                oList.push(oChilds[i])
            }
        }
        //  隔行变色
        oList.forEach(function (item, index) {
            item.style.backgroundColor = index % 2 == 0 ? "red" : "green"
        })
        // 5.children 微软 ie推荐 会在ie下,把注释当从元素节点
        console.log(box.children);
        for (var i = 0; i < box.children.length; i++) {
            if (i % 2 == 0) {
                box.children[i].style.backgroundColor = "yellow"
            } else {
                box.children[i].style.backgroundColor = "pink"
            }
        }

    </script>
</body>

</html>
兄弟节点

previousElementSibling前一个兄弟

nextElementSibling后埔一个兄弟

<ul>
        <li>我是第1</li>
        <li>我是第2</li>
        <li id="li3">我是第3</li>
        <li>我是第4</li>
        <li>我是第5</li>
    </ul>
    <script>
        // 前面一个previousElementSibling
        var li3 = document.querySelector("#li3");
        var pre = li3.previousElementSibling || li3.previousSibling
        pre.style.backgroundColor = "pink"
        // 后面一个
        var next = li3.nextElementSibling || li3.nextSibling
        next.style.backgroundColor = "skyblue"
    </script>

8节点的插入,替换,删除,克隆

1.插入

​ 父.insertBefore(新的节点,参照位置)

​ insertBefore()如果第二个参数为null,就等价于appendChild(),成为父元素里面最后位置元素

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>插前</button>
    <button>插后</button>
    <button>插到最后</button>
    <ul>
        <li>我是第1li</li>
        <li>我是第2li</li>
        <li id="li3">我是第3li</li>
        <li>我是第4li</li>
        <li>我是第5li</li>
    </ul>
    <script>
        var btn = document.querySelectorAll("button");
        var li3 = document.querySelector("#li3")
        // 父.insertBefore(新的节点,参照位置)
        // insertBefore()如果第二个参数为null,就等价于appendChild(),成为父元素里面最后位置元素
        //    插入到前面
        btn[0].onclick = function () {
            // 1.创建div元素
            var div = document.createElement("div");
            // 2.设置样式
            div.style.backgroundColor = "pink";
            // 3.设置元素的文本
            div.innerText = "我是动态创建的div"
            // 4.把div插入到li3的前面
            li3.parentNode.insertBefore(div, li3)
        }
        // 插入到后面
        btn[1].onclick = function () {
            // 1.创建元素
            var div = document.createElement("div");
            // 2.添加样式
            div.style.backgroundColor = "skyblue";
            // 3.添加文本
            div.innerHTML = "我是在后面插入的动态元素"
            // 4.把div插入到li3的后面
            var li4 = li3.nextElementSibling || li3.nextSibling;
            li4.parentNode.insertBefore(div, li4)

        }
        // 插入到最后
        btn[2].onclick=function(){
            // 1.创建div
            var div=document.createElement("div");
            // 2.设置文本
            div.innerHTML="我在最后插入"
            // 设置背景
            div.style.backgroundColor="red"
            // li3.parentNode.insertBefore(div,null)
            li3.parentNode.appendChild(div)
        }
    </script>
</body>

</html>
2.替换,删除

父.replaceChild(新创建的元素,要替换掉的原来的元素)

父.replaceChild(要删除的元素)

  <button>替换</button>
    <button>删除</button>
    <button>自杀</button>
    <ul>
        <li>我是第1</li>
        <li>我是第2</li>
        <li id="li3">我是第3</li>
        <li>我是第4</li>
        <li>我是第5</li>
    </ul>
    <script>
        var li3 = document.querySelector("#li3")
        var btn = document.querySelectorAll("button")
        // 一.替换
        // 父.replaceChild(新创建的元素,要替换掉的原来的元素)
        btn[0].onclick = function () {
            // 1.创建元素
            var div = document.createElement("div")
            // 2.创建文本元素
            var txt = document.createTextNode("我是替换元素")
            // 关联创建的元素和文本
            div.appendChild(txt)
            // 3.设置元素的颜色
            div.style.backgroundColor = "red";
            li3.parentNode.replaceChild(div, li3)
        }
        // 二.删除
        // 父.replaceChild(要删除的元素)
        btn[1].onclick = function () {
            li3.parentNode.replaceChild(li3)
        }
        // 自杀删除
        btn[2].onclick = function () {
            li3.remove()
        }
3.克隆

浅克隆 colonNode(false),只克隆自己,不能克隆子元素

深克隆 colonNode(true) 会自动克隆自己,还会克隆子元素,但是不会克隆事件

 <button>浅克隆</button>
    <button>深克隆</button>
    <div class="box">
        我是文字
        <div class="inner"></div>
    </div>
    <script>
        var btn=document.querySelectorAll("button")
        var box=document.querySelector(".box")
        // 浅克隆 colonNode(false),只克隆自己,不能克隆子元素
        btn[0].onclick=function(){
            var oColon=box.cloneNode(false);//在内存中
            // 把克隆的dom.添加到页面
            document.body.appendChild(oColon)
        }
        // 深克隆 colonNode(true) 会自动克隆自己,还会克隆子元素,但是不会克隆事件
        btn[1].onclick=function(){
            var oColon=box.cloneNode(true);//在内存中
             // 把克隆的dom.添加到页面
             document.body.appendChild(oColon)
        }
    </script>

9innerHtml,innerText,nodeValue;

innerHtml,innerText可以设置,也可以获取

​ 设置 innerText内容原封不动的显示

​ innerHTML如果遇到标签会被渲染

​ nodeValue通过childNodes获取到文本节点才能使用

10.类样式操作

添加add(),移出remove().切换toggle(),替换replace()

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;

        }

        .box.aaa {
            background-color: skyblue;
            width: 100px;
            height: 100px;
        }
		/* 注意这里不能有空格,否则不生效 */
        .box.bbb {
            border-radius: 50%;
            width: 100px;
            background-color: skyblue;
            height: 100px;
        }
    </style>
</head>

<body>
    <button>添加</button>
    <button>移出</button>
    <button>切换</button>
    <button>替换</button>
    <div class="box">
        我是盒子
    </div>
    <script>
        var btn = document.querySelectorAll("button");
        var box = document.querySelector(".box")
        // 1.添加类名
        btn[0].onclick = function () {
            box.classList.add("aaa")
        }
        // 2.移除类名
        btn[1].onclick = function () {
            box.classList.remove("aaa")
        }
        // 3.切换类名称
        btn[2].onclick = function () {
            box.classList.toggle("aaa")
        }
        // 4.替换类名称
        btn[3].onclick = function () {
            box.classList.replace("aaa", "bbb")
        }
    </script>
</body>

</html>

11.设置下标

 <button>我是按钮1</button>
    <button>我是按钮2</button>
    <button>我是按钮3</button>
    <button>我是按钮4</button>
    <button>我是按钮5</button>
    <button>我是按钮6</button>
    <button>我是按钮7</button>
    <button>我是按钮8</button>
    <button>我是按钮9</button>
    <button>我是按钮10</button>
    <script>
        var btn = document.querySelectorAll("button");
        // 循环是 同步代码
        // 延时器 定时器 事件都是异步
        console.dir(btn)
        for (var i = 0; i < btn.length; i++) {
            // 在遍历的过程中,给每个dom对象设置一个属性,值 是下标
            //    同步
            btn[i].index = i//设置值在前面
            // 异步
            btn[i].onclick = function () {
                console.dir(this)//点到那个按钮,this就是谁
                console.log(this.index);//获取值在后面
            }
        }
    </script>

案例排他思想

    <button>我是按钮1</button>
    <button>我是按钮2</button>
    <button>我是按钮3</button>
    <button>我是按钮4</button>
    <button>我是按钮5</button>
    <script>
        // 排他思想
        var btn = document.querySelectorAll("button")
       
        for (var i = 0; i < btn.length; i++) {
            btn[i].index = i//设置值
            btn[i].onclick = function () {
                // 鼠标点击了谁 ,this就指向谁
                // 点击后,把所有的按钮背景颜色设置为红色
                for (var j = 0; j < btn.length; j++) {
                    btn[j].style.backgroundColor = ""//清空颜色
                }
                // 再给当前的按钮,设置红色
                this.style.backgroundColor = "red"
                alert(this.index)//取值
            }
        }
    </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值