The Error of Getting an Element in JavaScript
Sometimes beginner programmers make a mistake
by using the querySelectorAll method
to get a single DOM element instead of the
querySelector method.
Let's look at the characteristic features of this error. Suppose there is a paragraph:
<p>text</p>
A certain programmer decided to get and change the text of this paragraph. To do this, he got a reference to this element into a variable, mistakenly using the wrong method:
let elem = document.querySelectorAll('p');
Then the programmer tried to change the text of the paragraph. However, the paragraph text did not change:
elem.textContent = '!!!'; // didn't work
At the same time, no error appeared in the console. The point is that a valid operation was performed, but not on one element, but on a group. And reading or changing the text of a group of elements just like that is impossible - only by looping through them and accessing each element individually.
How to Detect the Error
Let's see how a programmer should act to detect this error. In fact, with some experience, it is easy to detect by its characteristic signs.
Suppose, however, that this did not happen. Then
the programmer's first action when searching for errors
should be to output the variable values
to the console. In his case, there is only
one variable - elem. It is necessary to output the value
of this variable and see what
is in it:
let elem = document.querySelectorAll('p');
console.log(elem); // will output an array, not a single element
In the console, it is immediately clear that the variable contains not one element, but an array. This immediately gives an obvious hint that a mistake was made in the method for getting the element.