访问器属性原理与应用场景,获取 dom 元素的两个重要方法
一.访问器属性原理与应用场景
//常规写法
let teacher = {
data: {
class: "一班",
lesson: "语文",
},
getlesson() {
return this.data.lesson;
},
setlesson(lesson) {
this.data.lesson = lesson;
},
who() {
console.log(`${this.data.class}${this.data.lesson}老师`);
},
};
console.log(teacher.getlesson());
teacher.setlesson("数学");
teacher.who();
//访问器属性,将方法伪装成属性
//调用时使用属性访问语法的方法
teacher = {
data: {
class: "一班",
lesson: "语文",
},
get lesson() {
return this.data.lesson;
},
set lesson(lesson) {
this.data.lesson = lesson;
},
who() {
console.log(`${this.data.class}${this.lesson}老师`);
},
};
console.log(teacher.lesson);
teacher.lesson = "数学";
teacher.who();
二.获取 dom 元素的两个重要方法
//获取class为item的全部元素
const items = document.querySelectorAll(".item");
for (let index = 0; index < items.length; index++) {
items[index].style.color = "orange";
}
//获取class为item的第一个元素
const firstItem = document.querySelector(".item");
firstItem.style.color = "green";
//获取id为item2的元素
const secondItem = document.getElementById("item2");
secondItem.style.color = "blue";
//获取标题,头部,主体
console.log(document.title);
console.log(document.head);
console.log(document.body);
//获取整个html
console.log(document.documentElement);