DOM(Document Object Model 文档对象模型)
一、基本概念
- DOM分类:
- 核心DOM:用于任何结构化文档的标准模型
- HTML DOM:用于HTML文档的标准模型
- XML DOM:用于XML文档的标准模型
- DOM将HTML文档抽象为树,成为DOM树
- HTML中包含的节点:
- 文档结点:整个文档是一个文档节点
- 元素结点
- HTML 开始标签中的属性为元素节点对象的属性
- HTML 开始标签中的事件属性为元素节点对象的方法
- 元素节点对象中的方法函数中的 this 指向当前触发事件的元素
- 文本节点:空格、换行也是。HTML内的文本
- 属性节点:每个HTML属性是属性节点
- 注释节点
二、元素节点访问方法
关于元素节点获取,当通过id获取时,得到特定的一个,所以不是集合;
而通过类名或者标签名获取节点时,含有多个‘’元素‘’,所以是集合,所以要得到某一特定节点时,不要忘记下标。
2.1直接获取节点
//环境
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM</title>
</head>
<body>
<p>我喜欢的水果:</p>
<ul id="fruit">
<li>百香果</li>
<li>山竹</li>
<li class="red">火龙果</li>
<li>猕猴桃</li>
</ul>
<p>我喜欢的动物:</p>
<ul id="animal">
<li>小猴子</li>
<li>狮子</li>
<li class="red">小猪</li>
<li>大熊猫</li>
</ul>
</body>
</html>
-
id属性获得节点
//id获取节点 var fruit=document.getElementById('fruit'); // 变量存储 文档对象 调用文档函数 console.log(fruit); var animal=document.getElement('animal'); console.log(animal);
-
标签名获得所有同名标签
//标签获取 var p=document.getElementsByTagName('p');//类数组 console.log(p);
var p_2=document.getElementsByTagName('p')[1];
console.log(p_2);
-
类名获得所有类名相同的标签
//类名 var red=document.getElementsByClassName('red'); console.log(red);
var red_1=document.getElementsByClassName('red')[1]; console.log(red_1);
2.2 通过节点关系间接获取
- 通过父节点获得子节点
//找到所有子节点
var fruit=document.getElementById('fruit');
var fruitChild=fruit.childNodes;
for(var i=0;i<fruitChild.length;i++){
console.log(fruitChild[i]);
}
//所有元素子节点
var animal=document.getElementById('animal');
console.log(animal.children);
//DOM树获取首个子节点
console.log(animal.firstChild);
//节点获取首个元素子节点
console.log(animal.firstElementChild);
console.log(animal.firstElementChild.firstChild);
//最后一个子节点
//DOM树
console.log(animal.lastChild);
//元素树
console.log(animal.lastElementChild);
-
通过子节点获得父节点
//DOM树 animal.parentNode; //元素树 animal.parentElement;
节点树 元素树 获取父节点 parentNode parentElement 获取子节点 childNodes(所有的,集合) children(集合) 获取第一个子节点 firstChild firstElementChild 获取最后一个子节点 lastChild lastElementChild -
获得前后兄弟节点
节点树 元素树 获取前一个兄弟节点 previousSibling previousElementSibling 获取后一个兄弟节点 nextSibling nextElementSibling -
三个特殊节点
console.log(document.documentElement);
console.log(document.head);
console.log(document.body);
三、元素节点内容
- innerHTML
- 可以读取也可以修改
console.log(animal.children[2].innerHTML);
console.log(animal.innerHTML);
- innerHTML
四、元素节点属性
-
获取元素节点属性:node.getAttribute(attrName)
console.log(animal.children[2].getAttribute("class"));
-
设置元素节点属性
animal.children[2].setAttribute("class",'green'); console.log(animal.children[2].getAttribute("class"));
-
判断某一元素节点属性
console.log(animal.children[3].hasAttribute("class"));//false
-
删除某一元素节点属性
animal.children[3].setAttribute("class",'test');//设置属性 console.log(animal.children[3].getAttribute("class"));//test animal.children[3].removeAttribute("class");//删除 console.log(animal.children[3].getAttribute("class"));//false