'How can I solve Uncaught TypeError?
While trying to push element in array, I receive an error:
main.js:1 Uncaught TypeError: Cannot read properties of null (reading 'document') at main.js:1:50
Here is my code:
<!DOCTYPE html>
<html>
<body>
<button id="input">Click Here</button>
<script>
const newItem = document.getElementById('.input').document.addEventListener('click', function(addNewItem) {
let move = ["L", "L", "R", "F", "N"];
const newMove = move.push('newItem');
console.log(newMove);
})
</script>
</body>
</html>
Solution 1:[1]
There are two mistakes in your code.
- You are targeting the
id
by usingdocument.getElementById(".input")
, however; id in html isinput
not.input
. You have to remove.
beforeinput
.
- Remove
document
beforedocument.addEventListener
document.getElementById('input').addEventListener('click', function (arg) { });
I have included a modified example of your code below with the appropriate corrections.
<!DOCTYPE html>
<html>
<body>
<button id="input">Click Here</button>
<script>
const newItem = document.getElementById('input').addEventListener('click', function (addNewItem) {
let move = ["L", "L", "R", "F", "N"];
const newMove = move.push('newItem');
console.log(newMove);
});
</script>
</body>
</html>
Solution 2:[2]
The error is being caused by document.getElementById('.input')
. which returns null. There is not .input
element, you need to use the correct spelling, like this: 'input'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | j D3V |