By Adam Roberts

getElementsByTagName (W3C DOM Core method)

By Adam Roberts
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min




var paragraphs = document.getElementByTagName('p');

The example above gets a reference to the collection of p elements within the current document, and saves it to the variable paragraphs. The returned collection is live, which means that changes to the HTML it represents are immediately reflected in the collection, without having to retrieve it again.

This method can also be used contextually, to get a reference to the elements that are inside a specific element, for example:

var items = list.getElementByTagName('li');

So if the list in that example were a ul element, the items variable would refer to a collection of all the li elements that are inside that list.

The elements are retrieved in the linear order in which they appear in the document, ie. they correspond to a flattened view of the DOM. So if, in the previous example, the list corresponded with this HTML:


The returned collection would be in the following order:

  1. [0] Cheeses
  2. [1] Edam
  3. [2] Gouda
  4. [3] Cheddar
  5. [4] Hams
  6. [5] Prosciutto
  7. [6] Parma
  8. [7] Salami


name (DOMString) required
The tagName of the elements to match. The value * matches all elements.



Get an ordered list of all elements with a given tag name, that are descendents of this document or element, in the linear order in which they appear in the DOM tree.

The returned collection is a NodeList — an ordered collection of nodes, indexed numerically starting from zero. If there are no matching elements then it’s a collection with zero members.

A collection is not an array

Even though a collection looks like an array, it isn’t an array — although you can iterate through it and refer to its members like an array, you can’t use Array methods like push or pop on it.

Return value

A NodeList containing all the matched elements ; if no elements are found this will be a list with zero members.

Login or Create Account to Comment
Login Create Account
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?