Search code examples
javascriptdomgetelementbyid

How do you use document.getElementById( ) as part of a function with the target id being passed as the parameter


I am trying to target a button using document.getElementById. When the button is clicked I want the colour of the button to change to red.

My code currently looks as follows:

function selectDay (value) {
    var id = '"' + value + '"';
    console.log(id)
    document.getElementById(id).style.backgroundColor = "red";
}

When I check the value of id this is always correct.

For example, if a button is clicked that has an id of 1 then in the console I will have "1". document.getElementById("1") should work but instead I am getting an error stating:

Cannot read property 'style' of null.

I have double checked and the id in the html is definitely correct.


Solution

  • Remove the quotes, just use value directly: document.getElementById(value)

    You use quotes when writing IDs literally in your code because that's what tells JavaScript that what you're writing in the code is a string. But in your code, value is a parameter (almost identical to a variable). You want to use that parameter's value.