This error is showing up only when I have 2 different files for html and js. even if i add " document.addEventListener(‘DOMContentLoaded’, function() {
countEl.addEventListener("click", increment);
});"
Given below are the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./index.js"></script>
//<link rel="stylesheet" href="./index.css">
</head>
<body>
<h1>People entered:</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
<button id="save-btn" onclick="save()">SAVE</button>
</body>
</html>
let count = 0;
let countEl = document.getElementById("count-el")
function increment() {
count = count + 1;
countEl.innerText = count;
}
increment();
function save(){
console.log(count);
}
document.addEventListener('DOMContentLoaded', function() {
countEl.addEventListener("click", increment);
});
it either shows error for the line "countEl.innerText = count;" or for "INCREMENT" and "SAVE" button, the error shows for button if i remove listners is "Uncaught ReferenceError: increment is not defined" i want to make this work in two different file ie, html and js two seperate files. Refer to the image as well.
enter image description here
when click on increment button every time the count should be added +1. and when click on save the count should stop with the last cilcked number.
2
Answers
It’s because of page loading. when page is loading your DOM element is empty so it can’t find your preferred element. Change your JS code to this way, it will work for you.
I would suggest you take the script tag to the bottom of the body tag. It current position makes it load before the body DOM gets loaded.
Should be something like this:
Then fix the JavaScript a bit. I don’t see the need for adding click event listeners when using the onclick HTML attributes. Just call the function directly.
Hopefully this helps.