Chapter 4. Element Node Selection
4.1 Selecting a Specific Element Node
The most common methods for getting a reference to a single element node are:
querySelector()getElementById()
In the following code, I leverage both of these methods to select an element node from the HTML document.
<!DOCTYPE html> <html lang="en"> <body> <ul> <li>Hello</li> <li>big</li> <li>bad</li> <li id="last">world</li> </ul> <script> console.log(document.querySelector('li').textContent); //logs Hello console.log(document.getElementById('last').textContent); //logs world </script> </body> </html>
The getElementById() method is pretty simple
compared to the more robust querySelector() method. The
querySelector() method permits a parameter in the form
of a CSS
selector syntax. Basically, you can pass this method a CSS3
selector (e.g.,
#score>tbody>tr>td:nth-of-type(2)), which it
will use to select a single element in the DOM.
Notes
querySelector() will return the first node
element found in the document based on the selector. For example, in the
preceding code, I pass a selector that will select all the
<li> elements in CSS, but only the first one is
returned.
querySelector() is also defined on element
nodes. This allows the method to limit its results to a specific vein of
the DOM tree, thereby enabling context quering.
4.2 Selecting/Creating a List (a.k.a. NodeList) of Element Nodes
The most common methods for selecting/creating a list of nodes in an HTML document are:
querySelectorAll()getElementsByTagName() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access