getElementById is very frequently used to “latch onto” an element for manipulation.
Given any element on a page with an
id attribute on a page:
<div id="headlight"> … </div>
document.getElementById. Very frequently, the resulting object is set to a variable, making it much easier to refer to later.
var headlight = document.getElementById("headlight");
Note that it is “get element”, singular. This makes sense, since the
id value for an element must be unique on a web page: “get elements by id” would be a contradiction.
Displaying the value of the variable in the console would present the object:
console.log(headlight); > <div id="headlight"> … </div>
There’s a few things to note at this point:
- the variable is not required to have the same name as the element’s
idvalue, although it makes sense to do so (and is therefore a recommended practice).
getElementByID(and won’t be executed if it is).
- similarly, the
idvalue is case sensitive:
document.getElementById("Headlight")won’t work in this example.
- Unlike CSS, there’s no octothorpe (
#) used in front of the
idvalue when referencing it in
getElementById, since it’s clear we’re already referring to an
You may have come across the curious fact that modern browsers automatically create objects for any elements that have an
id. That is, loading a page that features the element example we’ve been using, and doing nothing else but going to the console to type this:
…will produce the same result as explicitly creating a variable, as we did earlier.
However, this should be considered a bug, rather than a feature: you should always explicitly reference an
id, rather than depending on this behaviour.
Unlike other methods that we will look at in this series,
getElementById is an exclusive method of the
document object, and is always associated with it: that is, it must always be written as
id attributes. While it remains very useful, greater flexibility and precision is usually provided by newer alternatives such as
querySelector, reducing the need for id values everywhere.
Photograph by Jon Matthies, used under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.