获取DOM元素
- document.getElementById([ID]) 基于元素的ID获取到这个元素
- document.body 获取页面中的BODY元素
- document.getElementByTagName([标签名]) 基于标签名获取到页面中所有的元素标签的集合
就算只有一个或没有,获取到的也是一个集合HTMLCollection(一个类数组:结构和数组非常相似,但不是数组)
基于JS获取到到的DOM元素是“对象数据类型”值,里边博阿含很多浏览器自带的、用来操作元素的键值对
对于DOM是对象的理解
获取到的元素是对象,储存在堆内存中,里边有很多键值对,正常对象中的键值对的操作都适用 box.id或box[“id”]
<div class="box">
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
</div>
document.getElementById('box');
/*
* id : "box" 存储元素的ID
* className : "box" 存储样式类的信息
* innerHTML : "..." 存储元素的内容
* tagName : "DIV" 存储元素的大写标签名
* // style存储的是当前元素的行内样式,只有把样式写在行内,才会在这里有
* style : BBFFFOOO(这是一个对象的地址)
* onclick : null 事件属性,点击时做的事情
* onmouseover : null 鼠标划过做的事情
*/
面试题1
document.getElementById('box');
let box = document.getElementById('id');
box.style.color = 'red';// 可以改变,因为box指向的是堆内存中的box
let boxSty = box.style;
boxSty.color = 'red'; // 可以改变,因为boxSty指向的是堆内存中的box.style
let text = box.style.color;
text = 'red'; // 不可以改变,因为text指向的是栈内存中的''(box.style.color = '')
要回答出元素对象的数据结构 + 堆栈内存机制
面试题2 (CSS中:nth-child可以搞定)
<div class="box">
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
</div>
let itemList = box.getElementByTagName("li");
/* 0 : 第一个LI对象
* 1 : 第二个LI对象
* ...
* length : 5
*/
for (var i = 0, i < itemList.legnth; i++) {
var itemLi = itemLi[i];
// Solution 1
itemLi.style.color = i % 2 != 0 ? 'white' : 'grey';
// Solution 2
switch(i % 2) {
case 0 :
itemLi.style.color = "white";
break;
default:
itemLi.style.color = 'grey';
}
}