Summary
-
There are 6 main methods to search for nodes in DOM:
querySelector
searches by CSS-selector, and can call on an element and is not livequerySelectorAll
searches by CSS-selector, and can call on an element and is not livegetElementById
searches byid
, and can only call ondocument
and is not livegetElementsByName
searches byname
, and can only call ondocument
and is livegetElementsByTagName
searches by tag or*
, and can call on an element, and is livegetElementsByClassName
searches by class, and can call on an element, and is live
-
By far the most used are
querySelector
andquerySelectorAll
, butgetElement(s)By*
can be helpful as well -
Using
document.getElementById
is preferred overid
directly to avoid confusion about where the variable comes from -
There is
elem.matches(css)
to check ifelem
matches the given CSS selector -
There is
elem.closest(css)
to look for the nearest ancestor that matches the given CSS-selector. Theelem
itself is also checked -
There is
elemA.contains(elemB)
returns true ifelemB
is insideelemA
or whenelemA==elemB
Tasks
-
Search for elements
// the table with id="age-table" let table = document.getElementById("age-table") // all label elements inside that table let labels = table.getElementsByTagName("label") // the first td in that table let firstTd = table.querySelector("td") // the form with name="search" let form = document.getElementsByName("search")[0] // the first input in that form let firstInput = form.querySelector("input") // the last input in that form let inputs = form.querySelectorAll("input") let LastInput = inputs[inputs.length - 1]