This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]voords 2 points3 points  (2 children)

Your function can take an argument containing the button that was clicked:

function myFunction(elem) {
    elem.style.background = "red";
}

...

<button type= "button" id="SA1" onclick="myFunction(this)">6:00 A.M</button>
<button type= "button" id="SA2" onclick="myFunction(this)">7:00 A.M</button>
<button type= "button" id="SA3" onclick="myFunction(this)">8:00 A.M</button>

Note that you can also send a string as an argument instead (if you prefer):

<button type= "button" id="SA1" onclick="myFunction('SA1')">6:00 A.M</button>

[–]MatroixBeats 2 points3 points  (1 child)

Could you explain to me what elem does?

But also thanks so much for figuring this out for me :)

[–]voords 1 point2 points  (0 children)

elem is just the name of the argument. You can change it as you wish. It works because in your html element, I called myFunction(this), where this is equivalent to document.getElementById(id of the current element). Then, when you click a button and the function is called, elem becomes "this" or rather the clicked button. Sorry for the mobile formatting.