Finding Things

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:

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:

Notes:

  1. Some of the methods return a collection of elements. This collection is not an array.

  2. The methods are available as document.something() or as element.something(). You can use the latter form to narrow down your search.

Arrays

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