Hi all,
I have a very basic JavaScript question, as I am very new to developing.
I am creating a simple program that includes an increment button, a label element to hold the value I am incrementing and I would literally just like the button to add 1 each time it is pressed.
My current code is as follows:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="stylesheet.css" rel="stylesheet">
<title>JavaScript Counter</title>
</head>
<body>
<div class="title">
<h1>Counter</h1>
<p>Please use the buttons below in order to achieve the desired number</p>
</div>
<div class="number">
<label for="incrementText" value="0">0</label>
</div>
<fieldset id="button">
<button type="button" class="increase" onclick="incrementButton()">Increase</button>
<button type="button" class="decrease" onclick="decrementButton()">Decrease</but ton>
<button type="reset" class="reset" onclick="resetButton()">Reset</button>
</fieldset>
<script src="script.js"></script>
</body>
</html>
JS:
function incrementButton() {
const element = document.getElementById('incrementText');
const val = element.innerHTML;
++val;
document.getElementById('incrementText').innerHTML = val;
}
When I run the HTML file in my browser, it returns the following errors:
TypeError: Cannot read properties of null (reading ‘innerHTML’)
at incrementButton (script.js:3:24)
at HTMLButtonElement.onclick (index.html:19:76)
How can it be reading a property of null?
Any help would be greatly appreciated!