1. What is Web API?
2. What is DOM? What is the DOM tree?
3. Get elements
DOM is mainly used to obtain operation elements in developing applications.
There are several ways to get elements:
- Get by ID
- Get by tag name
- Obtained through the new method of HTML5
- Special element acquisition
3.1 Get by ID
Use the getElementById() method to get an element object with an ID
//1.因为我们文档页面是从上往下加载,所以得先有标签,script写在标签下面
//2.get获得element元素by通过驼峰命名法
//3.参数 id 是一个对大小写敏感的字符串
//4.从输出的结果看,document.getElementById() 返回的是一个元素对象
<div id="time">2022-4-20</div>
<script>
var timer = document.getElementById('time')
console.log(timer);
console.log(typeof timer);
</script>
The output is:
3.2 Obtain according to the tag name
Use the getElementsByTagName() method to return a collection of objects with the specified tag name.
getElementsByTagName('tag name')
<ol>
<li>111</li>
<li>222</li>
<li>333</li>
<li>444</li>
</ol>
<script>
var lis = document.getElementsByTagName('li');
//获取的是一个伪数组的集合
//想要获取里面的所有元素对象我们可以通过遍历
for (i = 0;i <= lis.length; i++){
console.log(lis[i]);
}
//例子中的li有多个,返回的集合用数组存储。那么假如只有一个li呢?
//其实也是用数组存储,如果页面中没有li这个元素,那么返回的就是一个空的为数组的形式
</script>
The result is:
according to the label name, there is another form
<ol>
<li>111</li>
<li>222</li>
<li>333</li>
<li>444</li>
</ol>
<script>
var ols = document.getElementsByTagName('ol');
// console.log(ols.getElementsByTagName('li'));
//上面这种获取方式是错误的,因为getElementsByTagName()返回的是一个伪数组,为数组是不可以作为父元素的!!!必须指定道哪一个元素
console.log(ols[0].getElementsByTagName('li'))//这样就对了,指定了第一个ol
//因为父元素必须是指定的单个元素
//通常我们使用id
</script>
3.3 Obtained through the new method of H5