One of the things you will have to do in JavaScript is to fine one or more elements in the document. These may be elements that you have added using JavaScript, or they may be elements generated from the original HTML.
JavaScript has a number of methods to locate elements. Some have been around for a long time, and some are no longer as useful as they used to be. In fact, when we get to querySelector[All]()
, we’ll find that the older ones are no longer necessary in a modern browser.
Historically, the main Methods are:
getElementsByTagName()
getElementsByName()
These generate a live NodeList or HTMLCollection which is a numbered collection. It is not technically an array, and cannot use most of the array methods. It does, however, include a .length
property and elements can be referenced by number.
This is a live collection, so it will be automatically updated if any additions or deletions are made.
Modern HTML has deprecated the name
attribute for anything but forms, so getElementsByName()
is rarely useful. If you’re working with forms, you should use the form.elements
collection.
getElementsByClassName()
This is a bit late in coming; by the time all browsers supported this one it was all but supplanted by querySelectorAll()
below.
This also returns a live HTMLCollection of matching elements.
getElementById()
Unlike the others, this method returns a single element, as its name implies. It will give the first element matching the id
attribute. The id
is supposed to be unique, but not all developers do it properly.
This is a very commonly used method, though sometimes there are alternative ways of locating a single element.
querySelector()
This method uses a CSS selector to find a matching e
querySelectorAll()
This returns a static NodeList. That is, the collection is not updated if you happen to make any changes.
As with querySelector()
this method uses a CSS selector. The difference is that that it will always return a collection, even if there is only one element, unless, of course, there are no matches, in which case you get null
.
If you know that there is only one match, or if you’re only interested in the first, you should always use querySelector()
instead.
Others:
Some of the methods return a collection of elements. This collection is not an array.
The methods are available as document.something()
or as element.something()
. You can use the latter form to narrow down your search.
The methods which produce collections do not produce an array.
- The standard array methods do not apply to these collections.
- Some collections are dynamic, meaning that elements may have been added to or removed from the collection while you’re trying to process it.
getElementsByTagName()
This is a very old method which creates a collection of elements which match a tag. The collection is not an array.
document.getElementsByTagName()
Finds