⭐
DOM 结构以树的形态存在
。他提供了一系列API。这棵树由一系列节点组成,每个元素都是一个节点,节点类型种类实际非常繁多,但是常用的却比较固定,这里介绍四种:Document、Element、Text、Attribute
Document 就是指本份 html 文件。当浏览器载入 HTML 文档, 它就会成为 Document 对象。
Element 就是指 HTML 文件内的各个标签,像是下面这样的标签都属于 Element 。
、 、
- Text
Text 就是指被各个 Element 包起来的文字,像下面的 “我是标题h1”。
我是标题h1
- Attribute
Attribute 类型表示元素的特性。就是各个标签里的属性,比如 style。
DOM树
整个文件可以被看做是一个 document,根节点就是 HTML 这个 element。从 HTML 出发,各个要素构成了一颗DOM树
DOM 操作 这是div中的文字

DOM-API
DOM 提供了非常多的API提供DOM的增删改查操作,以下面的 html 为例介绍常用 API.
DOM 操作 这是标题h1
这是标题h2
这是一些文字

查询节点
常用的 DOM 节点查询API如下:
- getElementById : 按照 id 查询
- getElementsByTagName: 按照标签名查询
- getElementsByClassName : 按照类名查询
- querySelectorAll : 按照 css 选择器查询
//通过id获取容器const div1 = document.getElementById('div1')console.log('==========div1', div1)//通过类型获取const divList = document.getElementsByTagName('div') //集合console.log('==========divList',divList)//通过类名来获取const containerList = document.getElementsByClassName('container')console.log('==========containerList', containerList)//通过css选择器获取const divList2 = document.querySelectorAll('div') // 寻找标签为div类型的元素集合console.log('==========divList2',divList2)const redList = document.querySelectorAll('.red') // 寻找类名为red的元素集合console.log('==========redList',redList)
打印如下👇

新增节点
创建一个新节点h3,填充文字为:这是标题h3, 把它添加到 h2 节点的后面。
// 获取父节点const parentNode = document.getElementById('div1')// 创建新节点const h3Node = document.createElement('h3')// 设置节点内容h3Node.innerHTML = '这是标题h3'// 把新创建的元素插入父节点parentNode.appendChild(h3Node)

删除节点
将刚刚新建的h3节点删除。
// 获取父元素const targetParent = document.getElementById('div1')// 获取目标元素const targetNode = document.querySelectorAll('h3')[0]// 删除目标元素targetParent.removeChild(targetNode)
操作节点属性
property:对DOM的JS属性
修改,样式的修改不会对html标签产生影响;类名的修改会改变html
// 样式属性修改h2Node.style.width = '100px'h2Node.style.backgroundColor = 'green'console.log(h2Node.style.backgroundColor, '==========h2Node.style.bcColor')console.log(h2Node.style.width, '==========h2Node.style.width')// 类名修改h2Node.className = 'red'console.log(h2Node.className, '==========h2Node.className')

attribute:修改节点的属性,真正作用到节点属性,setAttribute
修改属性,getAttribute
查询属性
const h2Node = document.querySelectorAll('h2')[0]h2Node.setAttribute('secondName', 'Tom') //key-value形式console.log(h2Node.getAttribute('secondName'), '==========h2Node.getAttribute-data-name')h2Node.setAttribute('style', 'background-color:green') h2Node.setAttribute('class', 'red') h2Node.setAttribute('id', 'IDDD') console.log(h2Node.getAttribute('style'), '==========h2Node.getAttribute-style-bcColor')console.log(h2Node.getAttribute('class'), '==========h2Node.getAttribute-class')console.log(h2Node.getAttribute('id'), '==========h2Node.getAttribute-id')

总结
什么是DOM
- DOM元素
- DOM树
DOM-API
- 查询节点
- 新增节点
- 删除节点
- 操作节点属性
相关内容