CSS Selectors
basic selectors
// basic selectors:
div // <div> element (tag name selector)
#nav // id="nav" (id selector)
.warning // class="warning" (class selector)
p[lang="fr"] // <p lang="fr"> (attribute selector)
*[name="x"] // any element with attribute: name="x"
combinations of selectors
span.fatal.error // <span class="fatal error">
span[lang="fr"].warning // <span lang="fr" class="warning">
selectors related to DOM structure
// children/descendants
#log span // descendant (space): <span> descendant of [id="log"]
#log > span // direct child (>): <span> child of [id="log"]
body > h1:first-child // first <h1> child of <body>
// siblings
img + p // next sibling (+): <p> immediately after <img>
h2 ~ p // following sibling (~): <p> that follows <h2>
The return value of querySelectorAll() is not an array of Element objects. Instead, it is an iterable array-like object known as a NodeList.
NodeList objects
have a length property, can be indexed like arrays.
can loop with traditional for( ; ; ) loop, for-of loop, forEach() method.
can convert into array with Array.from().
However, some older browsers have not implemented NodeList.forEach()
nor Array.from()
. This can be circumvented by using Array.prototype.forEach()
— see this document's Example.
🛠️ CSS Diner
DOM ⟩ querying elements
Last updated