<aside> 🦄
the document object represents / models the webpage.
</aside>
<aside> 🦄
we can have html elements inside JavaScript
</aside>
the dom combines javascript and html together
document.querySelector() 是 JavaScript 中用于选取 DOM 元素的一个方法。它返回文档中匹配指定选择器的 第一个元素。如果没有找到匹配的元素,返回 null。
document.querySelector(selectors)
<aside> 🦄
let us get any element from the page and put it inside JavaScript .
</aside>
选取某个 ID 为 myId 的元素:
const element = document.querySelector('#myId');
选取类名为 myClass 的第一个元素:
const element = document.querySelector('.myClass');
选取页面中第一个 div 元素:
const element = document.querySelector('div');
选取嵌套元素:
const element = document.querySelector('div > .myClass');
选取多个元素:
const element = document.querySelector('p.myClass, h1');
querySelector() 只会返回 匹配的第一个元素,如果你想要返回所有匹配的元素,可以使用 document.querySelectorAll()。假设你有以下 HTML 代码: