Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Benjamin Wedemeyer
The "Cannot read property 'getElementsByTagName' of null" error occurs for 2 reasons:
getElementsByTagName()
method on a null
value (DOM element
that doesn't exist).Here is an example of how the error occurs.
const el = null; // ⛔️ Cannot read properties of null (reading 'getElementsByTagName') el.getElementsByTagName();
To solve the "Cannot read property 'getElementsByTagName' of null" error, make
sure you're using the correct id
when getting the DOM element. The error often
occurs after providing an invalid id
to the getElementById
method.
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'getElementsByTagName') const divs = el.getElementsByTagName('div');
We passed an id
that doesn't exist to the getElementById
method, so we got a
null
value back.
Trying to call the getElementsByTagName()
method on a null
value causes the
error.
To solve the "Cannot read property 'getElementsByTagName' of null" error, place the JS script tag at the bottom of the body tag, after the DOM elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script runs before div exists ⛔️ --> <script src="index.js"></script> <div id="box"> <div>Content 1</div> <div>Content 2</div> </div> </body> </html>
Notice that the JS script is placed above the div
element. The script is ran
before the div
element is created, therefore you can't access the div
in the
index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'getElementsByTagName') const divs = el.getElementsByTagName('div');
Instead move the JS script tag to the bottom of the body, after the DOM elements it tries to access.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <div>Content 1</div> <div>Content 2</div> </div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Now we can access the div
inside the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ div#box // ✅ Works const divs = el.getElementsByTagName('div'); console.log(divs); // HTMLCollection
The "Cannot read property 'getElementsByTagName' of null" error occurs when
trying to call the getElementsByTagName
method on a null
value.
To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.