A collection of luggage tags from around the world

The first of the “traditional” JavaScript selectors, 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:

  • as with getElementsByClassName, getElementsByTagName is 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 <main>)

  • the result of getElementsByTagName is returned as an HTMLCollection, an array-like structure that is automatically updated with any changes to the DOM.

  • the length method will show how many elements have been collected. In the console:

    tableHeaders.length;
    > 5
  • again like getElementsByClassName, getElementsByTagName can 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 id of flights, then the following JavaScript will gain <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 getElementsByTagName to 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 getElementsByTagNameNS.

document.body

Finally, there is one element that can be reached more directly than by using any JavaScript selector: document.body provides immediate access to the root body element.

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.