Forget about getElementById() and use meaningful ids

What getElementById() serves best is to pollute the code

Marian C.
CodeX

--

getElementById() seems to be essential. It figures in decent tutorials, many smart people seem to use it. It But why people prefer it to its alternatives?

In this post I search for advantages of getElementById() by comparing it to its two alternatives. I cannot find any solid advantage, instead I demonstrate some peculiarities of getElementById() and other approaches.

getElementById() alternatives

I start from a simple HTML file containing one div with id attribute a:

<div id="a">A</div>

I opened the file in Chrome and opened the console. I can retrieve the reference to the div using three approaches:

getElementById(elementId) returns the first element among document descendants whose id attribute equals elementId. It can be regarded as a specialized variant of more modern universal querySelector(). At first glance getElementById() does not seem do more than querySelector() and, judging from the screenshot, it is not even…

--

--

Marian C.
CodeX
Writer for

Java, JavaScript and SQL developer. Interested in data collection and visualization.