'Trying to change value of buttons

I'm trying to change the value of a button when I click on it, so what I did was I created a function in JavaScript where I call the ID of the element by getting the ID of the button and through style.backImage try and change it.

But it shows this error:

Uncaught TypeError: Cannot set properties of null (setting 'value')

This is the code of the button:

<button id="id1" style="margin: 17px;" onclick="mark()"> . </button>

And the JavaScript function is the following:

function mark(){
  document.getElementById(id1).style.backgroundImage = "url('cruz.webp')";
}

I've tried moving the JavaScript document from the head to body in HTML but hasn't done any good.

I know it must be really simple but I appreciate your help.



Solution 1:[1]

The issue with your code is in the JavaScript section of your code, with the function getElementById().


You need to change the parameter passed in getElementById() to be like below.

document.getElementById("id1");

The difference is that your code doesn't have id1 surrounded in quotes, but this answer has "id1" surrounded in quotes.


The reason your error is appearing is that the variable id1 (which is what JavaScript thinks) isn't defined, so getElementById() is returning null, which is what the error states (shown below).

Uncaught TypeError: Cannot set properties of null (setting 'value')

When you surround id1 with quotes, JavaScript should find the element and return an Element, which should stop the error from appearing and make your code work correctly.

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