1. 类数组
- 本身是对象
- 有length属性
- 有递增的索引
类数组可以转为数组并使用数组的方法操作
//结构类似数组,但是对象
const color = {
0: "white",
1: "blue",
2: "yellow",
3: "green",
length: 4
};
console.log(color);
//{0: "white", 1: "blue", 2: "yellow", 3: "green", length: 4}
console.log(color.length);
//4
console.log(color[2]);
//yellow
console.log(Array.isArray(color));
//false
console.log(typeof (color));
//object
console.log(color instanceof Object);
//true
//转为数组 方法 1
let arr = Array.from(color);
console.log(Array.isArray(arr));
//true
console.log(arr);
//["white", "blue", "yellow", "green"]
//转为数组 方法 2
Object.defineProperty(color, Symbol.iterator, {
value() {
let index = 0;
const keys = Object.keys(this);
return {
next: () => {
return {
done: index >= keys.length - 1,
value: this[keys[index++]]
};
}
};
}
});
// colors 数组
let colors = [...color];
console.log(Array.isArray(colors));
//true
//向colors末端添加一个元素
colors.push("orange");
console.log(colors);
// ["white", "blue", "yellow", "green", "orange"]
2. 获取DOM元素
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
- document.querySelectorAll() 获取满足条件的元素集合
const items = document.querySelectorAll(".list .item");
console.log(items);
//forEach
//item:当前元素(必须)
//index:索引(可选)
//items: 遍历的数组(可选)
items.forEach(function (item, index, items) {
console.log(index);
console.log(item);
})
//简化
items.forEach((item) => console.log(item));
//NodeList内置迭代器接口, 可用for...of遍历
for (const iterator of items) {
console.log(iterator);
}
- document.querySelector 获取满足条件的元素集合 的第一个元素
//获取满足条件的元素集合 的第一个元素
first = document.querySelector(".list .item");
console.log(first);
first.style.background = "skyblue";
let list = document.querySelector(".list");
console.log(list);
- 获取特定元素
//快速获取特定元素
//body
console.log(document.body);
//head
console.log(document.head);
//title
console.log(document.title);
//html
console.log(document.documentElement);
3. DOM树遍历
DOM树中所有内容都是节点(node)
例:
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
遍历
let nodes = document.querySelector(".list");
console.log(nodes.childNodes);
// console.log(nodes.children);
let items = nodes.children;
//得到的是 类数组
//转为数组
let arr = [...items];
arr.forEach(element =>
console.log(element)
);
//第一个元素
let first = arr[0];
first.style.background = "lightgrey";
console.log("first: ", first);
//最后一个元素
let last = arr[arr.length - 1];
last.style.background = "lightblue";
console.log("last: ", last);
//第二个元素
let second = first.nextElementSibling;
second.style.background = "yellow";
//倒数第二个
let secondLast = last.previousElementSibling;
secondLast.style.background = "orange";
4. 向元素内添加文本
- textContent 添加文本(HTML标签也会被当作文本)
- innerHTML 添加文本,会解析HTML标签
- outerHTML 替换父节点
<p></p>
使用p.textContent
const p = document.querySelector("p");
//向p标签添加文本
p.textContent = "<b>hahaha</b>";
显示:
使用p.innerHTML
p.innerHTML = "<b>hahaha</b>";
显示:
使用p.outerHTML
p.outerHTML = "<b>hehe</b>";
父节点的p标签没了
5. 获取元素的自定义属性
- 内置的标准属性,如id,可以直接用querySelector()访问
- 自定义的属性,通过在属性名前添加data-,然后使用dataset访问
<body>
<div id="a" class="user" name="haha"></div>
<script>
const user = document.querySelector("div");
console.log(user.className);
console.log(user.id);
console.log(user.name);
</script>
</body>
输出:
修改后name为data-name后:
<body>
<div id="a" class="user" data-name="haha"></div>
<script>
const user = document.querySelector("div");
console.log(user.className);
console.log(user.id);
console.log(user.dataset.name);
</script>
</body>
若属性名是多个单词使用-分隔的,如user-age, 获取属性时用驼峰命名法,即userAge获取
<body>
<div id="a" class="user" data-name="haha" data-user-age="6"></div>
<script>
const user = document.querySelector("div");
console.log(user.className);
console.log(user.id);
console.log(user.dataset.name);
console.log(user.dataset.userAge);
</script>
</body>
6. DOM元素增删改查
6.1 创建DOM元素
- document.createElement()
//创建DOM元素
let div = document.createElement("div");
console.log(div);
let span = document.createElement("span");
span.textContent = "Hey";
console.log(span);
6.2 添加,克隆元素
- 同一个元素只能被添加到一个位置
- 如果向不移动原来的元素,使用克隆方法
6.2.1 向父元素内的头部/尾部添加
- append(element)
- 向父元素内的末尾添加元素或文本,可同时添加多个(参数)
//创建DOM元素
let div = document.createElement("div");
console.log(div);
let span = document.createElement("span");
span.textContent = "Hey";
console.log(span);
//添加到div中
div.append(span, "aaa", "bbb");
向body中添加以显示元素
//向body中添加以显示元素
document.body.append(div);
向body中添加span,div中的span会被剪切,因为只能插入一个位置
document.body.append(span);
- 使用element.cloneNode(true)使元素复制后被添加
document.body.append(span.cloneNode(true));
- 使用append()创建ul列表
//用append()创建列表
const ul = document.createElement("ul");
//for...loop
for (let index = 1; index < 6; index++) {
const element = document.createElement("li");
element.textContent = `li${index}`;
element.style.color = "blue";
element.style.listStyle = "none";
ul.append(element);
}
document.body.append(ul);
- prepend(element)
- 向父元素内的头部添加元素或文本,可同时添加多个(参数)
//prepend() 在选定父元素头部添加元素
let title = document.createElement("p");
title.innerHTML = "<b>this is an unordered list created via javascript</b>";
ul.prepend(title);
6.2.2 向选定参考节点的前后添加
- before()
- after()
- 在选定 参考节点 的前后添加
选中参考节点
const referNode = document.querySelector("li:nth-of-type(3)");
referNode.style.background = "yellow";
在其之前,之后分别添加一个元素
const referNode = document.querySelector("li:nth-of-type(3)");
referNode.style.background = "yellow";
//before
let new1 = document.createElement("li");
new1.textContent = "new 01 before reference node";
new1.style.background = "lightgrey";
referNode.before(new1);
//after
let new2 = document.createElement("li");
new2.textContent = "new 02 after reference node";
new2.style.background = "skyblue";
referNode.after(new2);
6.3 替换元素
- replaceWith() 替换节点
let a = document.createElement("a");
a.textContent = "PHP.cn (This was item3)";
a.href = "https://php.cn";
referNode.replaceWith(a);
6.4 删除元素
- remove()删除节点
ul.querySelector("ul>li:last-of-type").remove();
6.5 插入元素
- insertAdjacentElement(position,element)
- 向元素的 起始标签/结束标签 的 前/后 添加
- 插入位置可为:
- beforebegin
- afterbegin
- beforeend
- afterend
const ul = document.createElement("ul")
ul.style.listStyle = "none";
ul.style.border = "1px solid black"
for (let index = 1; index < 6; index++) {
const element = document.createElement("li");
element.textContent = `item${index}`;
ul.append(element);
}
document.body.append(ul);
//using insertAdjacentElement(position,element)
let p = document.createElement("p");
p.textContent = "insertAdjacentElement-beforebegin"
ul.insertAdjacentElement("beforebegin", p)
let li1 = document.createElement("li");
li1.textContent = "insertAdjacentElement-afterbegin";
ul.insertAdjacentElement("afterbegin", li1);
- insertAdjacentHTML(position,HTML tags)
- 直接插入HTML标签及内容,省略createElement()步骤
ul.insertAdjacentHTML("beforeend", "<li>insertAdjacentHTML-beforeend</li>")
- insertAdjacentText()
- 只能插入文本
let p2 = document.createElement("p");
ul.insertAdjacentElement("afterend", p2);
p2.insertAdjacentText("beforeend", "insertAdjacentText");
7. CSS样式操作
7.1 行内样式
- element.style.attribute = “value”;
<body>
<p>Bonjour</p>
<script>
const p = document.querySelector("p");
p.style.textDecoration = "underline";
</script>
</body>
7.2 类样式
- element.classList.add(className1,className2…)
<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>
.bg-yellow {
background-color: yellow;
}
.bg-yellowgreen {
background-color: yellowgreen;
}
.border {
border: 1px slateblue solid;
}
</style>
</head>
<body>
<p>Bonjour</p>
<script>
const p = document.querySelector("p");
//1. 行内样式
p.style.textDecoration = "underline";
//2. 类样式
p.classList.add("bg-yellow", "border");
</script>
</body>
- element.classList.replace()
- element.classList.remove()
p.classList.add("bg-yellow", "border");
p.classList.remove("border");
p.classList.replace("bg-yellow", "bg-yellowgreen");
- element.classList.toggle()
- 相当于一个类样式的开关,有则关闭,无则打开
p.classList.add("bg-yellow", "border");
p.classList.remove("border");
p.classList.replace("bg-yellow", "bg-yellowgreen");
p.classList.toggle("border");
7.3 计算样式 (只可读取)
let styles = window.getComputedStyle(p, null);
console.log(styles.getPropertyValue("height"));
console.log(styles.getPropertyValue("color"));
console.log(styles.getPropertyValue("background-color"));
//也可用
let sts = document.defaultView.getComputedStyle(p, null);
console.log(sts.getPropertyValue("color"));