属性访问器与常用节点操作函数
<!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>
</head>
<body>
<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>
<script>
// 作业内容:
// 1. 实例演示"访问器属性",例如商品金额计算;
// 2. 实例演示dom元素的获取,遍历与增删,方法不限于课堂上提及的,更多的可查阅mdn手册;
// 访问权属性
let Person = {
data:{id:1,name:"华为笔记本",price:4980},
get price(){
return this.data.price;
},
set price(age){
return this.data.price = price;
},
};
console.log("笔记本价格:" + Person.data.price)
console.log("笔记本价格合计:" + Person.data.price * 2);
// 获取dom元素
const items = document.querySelectorAll(".list .item");//获取list 下所有子节点
let ulList = document.querySelector(".list");
console.log(ulList.childNodes);//不区分节点类型
console.log(ulList.children);//只返回元素类型的节点
// 遍历dom元素
[...ulList.children].forEach(items => (items.style.color = "red"));//用归并展开,遍历ul 中节点
const li1 = document.querySelector(".item:nth-of-type(3)"); //指定获取某一个节点
console.log(li1);
// 添加节点
let div1 = document.createElement("div");//创建div 节点
document.body.append(div1); //将div节点写入到文档(body中)
let h3 = document.createElement("h3");//创建h3节点
h3.textContent = "Hello Word";//h3赋值
div1.append(h3);//将h3节点写入到文档(div中)
// 删除节点
let div2 = document.createElement("div");
document.body.append(div2);
let h1 = document.createElement("h1");
h1.textContent = "删除的节点";
div2.append(h1);
div2.removeChild(h1);
</script>
</body>
</html>