Element节点
我们平时创建的div、p、span等元素在DOM中表示为Element元素
详细文档可参考MDN
我们来看一下常见的属性和方法:
常见属性
- 子元素 children childNodes
- tagName
- id/class
- clientWidth/clientHeight
- clientLeft/clientTop
- offsetLeft/offsetTop
常见方法
获取样式 getAttribute 修改某个样式 setAttribute
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #box { width: 200px; height: 200px; background-color: red; } .content { width: 100px; height: 100px; display: inline-block; background-color: blue; } </style> </head> <body> <div id="box" class="abc why" age="18"> <span name="why" class="content">span元素</span> <!-- 哈哈哈 --> <strong></strong> <a href="#"></a> </div> <div></div> <script> const divEl = document.querySelector("#box") // 1. 获取子元素 console.log(divEl.children) console.log(divEl.childNodes) // 2.tagName 如DIV console.log(divEl.tagName) // 3. id/class console.log(divEl.id) console.log(divEl.className) console.log(divEl.classList) // 4.在可视区域大小 console.log(divEl.clientWidth) console.log(divEl.clientHeight) console.log(divEl.offsetLeft) console.log(divEl.offsetTop) </script> // 常见的方法 const value = divEl.getAttribute("age") console.log(value) divEl.setAttribute("height", 1.88) </body> </html>
其他
text节点
文本节点由Text类型标识,顾名思义,dom中的文字
comment 节点
Comment代表注释节点,顾名思义,html 中写的注释
Attr 节点
元素的特性在DOM中以Attr类型表示。掌握name和value即可
<html> <body> <div id="myDiv" title="hello"></div> </body> <script> var div = document.getElementById('myDiv'); console.log(div.getAttributeNode('title').name); // "title" console.log(div.getAttributeNode('title').value); // "hello" </script> </html>
总结
这篇文章我们通过很多简单的代码,介绍了DOM的构成,希望大家有个系统的认识,下篇文章我们会用图来重新解释dom,图解dom.