Следите за новинками
в нашем Telegram канале. Жми, чтобы подписаться:)
3 of 17 menu
◀ ▶

The Error of Accessing an Array of Elements in JavaScript

Sometimes beginner programmers try to work with an array of elements as if they had a single element. Let's see what the essence of this error is.

Let the following paragraphs be given:

<p>1</p> <p>2</p> <p>3</p>

Suppose a certain programmer decided to write the same value into the text of each paragraph. To do this, they got references to these elements into a variable:

let elems = document.querySelectorAll('p');

Then our programmer mistakenly accessed our variable as if it contained a single element, not an array. As a result, the text of the paragraphs will not change, but, characteristically, there will be no error in the console either:

elems.textContent = '!';

The correct solution here would be to loop through the array of elements and perform the required operation for each element separately:

for (let elem of elems) { elem.textContent = '!'; }
← →
↑
English▼
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline