Increment Button

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!

if you look at the line of code it is referring to:

Then check the html code you wrote. Can you find any element whose id is incrementText? I couldn’t. So this getElementById is returning a null.

incrementText refers to the label element, which has div of class=‘number’ as the parent element. This is the element that I am trying to increment.

This element also has a value of 0 - so would it not return zero as the value, as opposed to null (which is an absence of value, I believe?).

getElementById is literally looking for an element that has the requested id.
In your html, there are NO elements with that id.

1 Like

Oh dear, sorry about that :rofl:

I see that it is a FOR attribute, what an idiot.

Thanks for pointing that out - not sure how i managed that.

no worries. I was going to be more specific but I preferred to let you find the issue yourself. (we’ve all done the same mistake, trust me)

1 Like