The headlight, grill and red hood of a sports car

One of the earliest and most fundamental means of referencing an element in JavaScript, 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>

can reference this element using 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 id value, although it makes sense to do so (and is therefore a recommended practice).
  • getElementById, like all JavaScript, is case-sensitive; it can’t be written as getElementByID (and won’t be executed if it is).
  • similarly, the id value is case sensitive: document.getElementById("Headlight") won’t work in this example.
  • Unlike CSS, there’s no octothorpe (#) used in front of the id value when referencing it in getElementById, since it’s clear we’re already referring to an id.

Auto Id?

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:

> headlight

…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.

Exclusivity

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 document.getElementById().

Conclusion

Historically, getElementById was used a great deal in JavaScript, which tended to leave markup littered with 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.