🔰querying elements
JS ⟩ browser ⟩ DOM ⟩ selecting elements
- Element ⟩ - .closest() - 往上選。 
- .querySelector() - 往下選。 
- .querySelectorAll() - returns NodeList. 
- .matches() - 只跟自己比較,不往上選,也不往下選。 
 
- Document ⟩ 
- DocumentFragment ⟩ 
- using components - do not query web components too early. 
The return value of querySelectorAll() is not an array of Element objects. Instead, it is an iterable array-like object known as a NodeList.
- querySelector(),- querySelectorAll()return a static NodeList.
- Node.childNodesis a live NodeList.
Some older browsers have not implemented NodeList.forEach() nor Array.from(). This can be circumvented by using Array.prototype.forEach()  👉 💈範例
- ::first-lineand- ::first-letterpseudo-elements match portions of text nodes rather than actual elements, they will not match if used with querySelectorAll() or querySelector().
- many browsers will refuse to return matches for the - :linkand- :visitedpseudo-classes.
// ⭐️ traditional for-loop
for (let i = 0; i < nodeList.length; i++) {
  let node = nodeList[i];
}
// ⭐️ for-of loop
const list = document.querySelectorAll('input[type=checkbox]');
for (let checkbox of list) {
  checkbox.checked = true;
}
// ⭐️ for browsers which don't support NodeList.forEach()
Array.prototype.forEach.call(list, (checkbox) => {
  checkbox.checked = true;
});Last updated
Was this helpful?