<!DOCTYPE html>
<html lang="zh-CN">
<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>获取元素</title>
</head>
<body>
<p id="date">2022-02-11</p>
<ul>
<li>列表1</li>
<li>列表2</li>
<li>列表3</li>
</ul>
<script>
let date = document.getElementById('date')
/*
* 返回伪数组li的集合,如果没有li伪数组元素就为空
*/
let list = document.getElementsByTagName('li')
let alter = document.getElementsByClassName('alter')
// querySelector(选择器) 选择第一个匹配的对象
let query = document.querySelector('.alter')
// querySelectorAll(选择器) 选择所有匹配的对象
let queryAll = document.querySelectorAll('.alter')
console.log(date) // <p id="date">2022-02-11</p>
console.dir(date) // 打印对象内容,显示对象属性和方法
console.log(list) // [li, li, li] (伪数组)
console.log(list[0]) // <li>列表1</li>
console.log(alter) // [ul.alter, p.alter] (伪数组)
console.log(alter[1]) // <p class="alter">alter</p>
console.log(query) // <ul class="alter">...</ul>
query = document.querySelector('#date')
console.log(query) // <p id="date">2022-02-11</p>
console.log(queryAll) // [ul.alter, p.alter] (伪数组)
</script>
</body>
</html>
获取<body>
和<html>
let body = document.body
console.log(body)
let html = document.documentElement
console.log(html)