Reputation: 1
I'm looking to target an element in the DOM as I would with getElementById(), but solely by clicking on it. For example, I want to turn the following div from red to green (below is the standard way):
function changeColor(element, value)
{
document.getElementById(element).style.background = value;
}
<div id="square" style="height: 100px; width: 100px;
background:red;" onClick="changeColor('square', 'green');"></div>
...but I want to do something like this:
function changeColor(THIS, value)
{
THIS('element receiving the click').style.background = value;
}
Does anyone know if this is possible?
Upvotes: 0
Views: 49
Reputation: 782785
In your code you can use document.getElementById
:
function changeColor(id, value) {
document.getElementById(id).style.backgroundColor = value;
}
But a better way is to use this
in the function call, as it's automatically set to the element that was clicked on.
onclick="changeColor(this, 'green')"
Then the function will receive the element as an argument:
function changeColor(element, value) {
element.style.backgroundColor = value;
}
Upvotes: 2