10.DOM文档对象模型
1.DOM节点的组成
元素节点 属性节点 文本节点
标签就是元素节点
class id的值 等 就是属性节点
文字,空格,换行就是文本节点
<div class="box">你好</div><元素节点 属性节点>文本不节点</元素节点>
2如何获取页面元素
-
根据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>
-
根据标签名获取
使用getElementByTagName()方法返回带有指定标签名的对象的集合
注意:
- 因为得到的是一个对象的集合,所以我们想要操作里面的元素就需要遍历
- 得到元素对象是动态的
<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>
-
通过HTML5新增的方法获取
-
document.getElementByClassName(‘类名’);//根据类名返回元素对象的集合
// 通过document.getElementsByClassName根据类名获取某些元素的集合var boxs = document.getElementsByClassName('box');console.log(boxs); //HTMLCollection(2) [div.box, div.box]
-
document.querySelector(‘选择器’)//返回指定选择器第一元素对象,切记里面的选择器是需要加符号的 .box #nav 等
// querySelector返回指定选择器的第一个元素对象var firstBox = document.querySelector('.box');console.log(firstBox);var nav = document.querySelector('#nav');console.log(nav); //div#nav
-
document.querySelectorAll(‘选择器’)//根据指定选择器返回
// querySelectorAll ()返回指定选择器所有元素对象的集合var allBox = document.querySelectorAll('.box');console.log(allBox);var lis = document.querySelectorAll('li');console.log(lis);
var oList = document.querySelectorAll(".cls")//NodeListoList.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"}
-
-
特殊元素获取
-
获取body元素
document.body //返回body元素对象
-
获取html对象
document.documentElement //返回html元素对象
-
3节点的分类
- 元素节点(1):box.nodeType
- 属性节点(2)box.attributes[0].nodeType
- 文本节点(3)box.childNodes[0].nodeType
- 注释节点(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);//boxconsole.log(box.attributes[1].nodeName);//idconsole.log(box.attributes[1].nodeValue);//idconsole.log(box.attributes[2].nodeName);//styleconsole.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属性的操作
- 查看属性 attribute获取当前dom的所有属性
- 获取属性 getAttribute(“属性的名称”) 返回属性的值
- 设置属性setAttribute(“属性名称”,“属性的值”)
- 移出属性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.获取domvar btn = document.querySelector("button");btn.onclick = function () {// 2.创建节点var div = document.createElement("div");//3.添加行内样式1div.style.height = "200px";div.style.width = "200px";div.style.borderRadius = "50%";// 4.添加类样式2div.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");// 给父节点添加背景色位pinkli3.parentNode.style.backgroundColor = "pink";var box = document.querySelector(".box")// // 1.前面的儿子console.log(box.firstChild);//#textconsole.log(box.firstElementChild);//在IE下,firstElementChild返回的是null// 兼容写法var oChild = box.firstElementChild || box.firstChildoChild.style.backgroundColor = "red"// 2.后面的儿子var oLast = box.lastElementChild || box.lastChildoLast.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>// 前面一个previousElementSiblingvar li3 = document.querySelector("#li3");var pre = li3.previousElementSibling || li3.previousSiblingpre.style.backgroundColor = "pink"// 后面一个var next = li3.nextElementSibling || li3.nextSiblingnext.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.创建divvar 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>