Array-like DOM objects

There are various array-like objects used in the Document Object Model to group information (typically sequences of objects). Individual elements can be accessed using the index and the length can be determined using length, but not all array methods are supported.

Methods called on the document object

All of the following are methods that can be called on the document object:

Name Meaning
.forms() all form elements in the body
.images() all image elements in the body
.links() all hyperlink elements in the body
.getElementsByClassName(class) elements with the specified class name
.getElementsByTagName(tag) elements with the specified tag name
.getElementsByName(name) elements with the specified name (as in forms)

Methods called on any object

All of the following are methods that can be called on any DOM object:

Name Meaning
.childNodes() all children
.getElementsByClassName(class) children with the specified class name
.getElementsByTagName(tag) children with the specified tag name

One of the challenges of changing a web page is that some of the array-like objects that are returned are live, meaning that they are refreshed and updated when changes take place. It is important to know whether what is returned is live or not.

Using selectors

The method .querySelectorAll(selector) consumes a selectorA way of specifying to which parts of a document the declarations in a rule apply. string and returns an array-like object containing all the matching elements. This is not a live object (unlike that returned by getElementsByTagName). The method .querySelector(selector) returns the first matching element or, if no elements match, null.

Selectors follow the syntax of CSS, which can be reviewed in the module on selectors in Web basics. Example selectors include p, .classname, p .classname, p > .classname and so on.