I'm trying to build something very simple, every time i click the button it increments the amount inside the html by 1, but it doesn't work and i don't know why:
let increment = document.getElementById("increment")
let counter = document.getElementById("counter")
let count = 0
increment.addEventListener("click",adding)
function adding() {
count +=1
counter.textContent += count
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div class="frame">
<div class="counter">0</div>
<button id="increment" onclick="adding()"> Click</button>
<button id="reset"> Reset</button>
</div>
<script src="test.js"></script>
</body>
</html>
You need to define the selector in you tag: <div class="counter">0</div> . Add id="counter"
Then change counter.textContent = count++ instead counter.textContent += count+=1
let increment = document.getElementById("increment")
let counter = document.getElementById("counter")
let count = 0
increment.addEventListener("click",adding)
function adding() {
counter.textContent = count
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div class="frame">
<div id="counter" class="counter">0</div>
<button id="increment" onclick="adding()"> Click</button>
<button id="reset"> Reset</button>
</div>
<script src="test.js"></script>
</body>
</html>
Try this instead. using onclick and the addEventListener make the function run twice, so the increment is always +2.
choose only one of the two triggers
let increment = document.getElementById("increment")
let counter = document.getElementById("counter")
let count = 0
increment.addEventListener("click",adding)
function adding() {
count +=1
counter.textContent = count
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div class="frame">
<div id="counter" class="counter">0</div>
<button id="increment"> Click</button>
<button id="reset"> Reset</button>
</div>
<script src="test.js"></script>
</body>
</html>
There are multiple things wrong with your code.
id of the div to counter instead of its class. As you are retrieving the elements using its id in the javascript.onclick='adding()' and a second time in javascript with increment.addEventListener("click",adding), which causes it to increment twice on each click.let increment = document.getElementById("increment")
let counter = document.getElementById("counter")
let count = 0
function adding() {
counter.textContent = ++count
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div class="frame">
<div id="counter">0</div>
<button id="increment" onclick="adding()"> Click</button>
<button id="reset"> Reset</button>
</div>
<script src="test.js"></script>
</body>
</html>