getElementsByTagName does exactly what it says, creating an
HTMLCollection of elements from a web page. The result of the method is usually set to the value of a variable:
var tableHeaders = document.getElementsByTagName("th");
A few notes:
getElementsByTagNameis always written in the plural, and always assumes that there are multiple instances of any element on the page (even with elements that should appear only once, such
the result of
getElementsByTagNameis returned as an
HTMLCollection, an array-like structure that is automatically updated with any changes to the DOM.
lengthmethod will show how many elements have been collected. In the console:
tableHeaders.length; > 5
getElementsByTagNamecan work from any element on the page, gathering matching children of that element (not including the element itself). If we have a table with an
<td>cells exclusively from that table:
var flightTable = document.getElementById("flights"), cells = flightTable.getElementsByTagName("td");
Alternatively, as a single line of code:
var cells = document.getElementById("flights").getElementsByTagName("td");
the universal selector (
*) works in
getElementsByTagNameto get all elements in a target.
getElementsByTagName always converts its argument into lowercase before searching the document, which leads to issues when searching the camelCased elements of SVG documents embedded in an HTML document. For this application, use the related
document.body provides immediate access to the root
Photographs by Alan Davey, Alwyn Ladell and Calsidyrose, licensed under Creative Commons.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.