Home > OS >  trying to change value of buttons
trying to change value of buttons

Time:04-08

I'm trying to change the value of a button when I click on it, so what I did is I created a function in js where i call the id of the element by getting the id of the button and through style.backImage try and change it. but 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 js function is the following

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

I've tried moving the js 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.

CodePudding user response:

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 because the variable id1 (which is what JavaScirpt thinks) isn't defined, so getElementById is returning null, which is what the error states (shown below; higlighted with tildes).

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 rid the error and make your code work correctly.

  • Related