1.两个获取元素的api
<!DOCTYPE html>
<html lang="zh-CN">
<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>获取dom元素</title>
</head>
<body>
<ul class="list">
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<script>
// 1.querySelectorAll:集合
const items = document.querySelectorAll(".list>li");
// items : 类数组(对象)
console.log(items, Array.isArray(items));
items.forEach(item => (item.style.border = "1px solid blue"));
// 2.querySelector:集合中的第一个
// 匹配满足条件的集合的第一个元素
const item = document.querySelector(".list>li");
console.log(item);
item.style.color = "red";
const list = document.querySelector(".list");
console.log(list);
const lis = list.querySelectorAll("li");
console.log(lis);
lis.forEach(li => (li.style.color = "green"));
</script>
</ul>
</body>
</html>
2.dom常用的遍历方法
<!DOCTYPE html>
<html lang="zh-CN">
<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>dom遍历</title>
</head>
<body>
<ul class="list">
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
</ul>
<script>
/**
* *节点类型(12个,常用3个)
* * 1. document: 文档类型, 9
* * 2. element: 元素类型, 1
* * 3. text: 文本类型, 3
**/
let list = document.querySelector(".list");
console.log(list.nodeType);
// 1.所有子节点:childNodes
let items = list.childNodes;
console.log(items);
// 2.所有子元素节点:children
console.log(list.children);
// 3.第一个子元素;firstElementChild
console.log(list.children[0].textContent);
console.log(list.firstElementChild.textContent);
// 4.下一个兄弟:nextElementSibling
console.log(list.querySelector(":first-child + *").textContent);
console.log(list.firstElementChild.nextElementSibling.textContent);
// 5.最后一个兄弟:lastElementChild
console.log(list.lastElementChild.textContent);
// 6.前一个兄弟:previousElementSibling
console.log(list.lastElementChild.previousElementSibling.textContent);
// 7.父节点:parentNode
console.log(list.firstElementChild.parentNode);
// 8.遍历
[...list.children].forEach(item => (item.style.color = "red"));
</script>
</body>
</html>