'Changing specific element with the same function [duplicate]

So I want to code a Vanilla Script which changes the style of a text individually. Heres the code of it:

<body>
<p class="black_to_red" onclick="get_red()">If I click this, I am red</p>
<p class="black_to_red" onclick="get_red()">If I click this, I am red</p>
<script>
function get_red() {
    text = document.getElementsByClassName("black_to_red");
    for (let i = 0; i < text.length; i++) {
        text[i].style.color = 'red';
    }
}
</script>
</body>

But this code only works kinda. The reason why I say "kinda" is because when I click on a text it changes the style of both textes. Is there a way to make it only effect the specific text I click on it?



Solution 1:[1]

There are several ways to do that.

If you stick with onclick attributes, then pass this as argument, so the function knows which element got the click event.

function get_red(elem) {
    elem.style.color = 'red';
}
<p class="black_to_red" onclick="get_red(this)">If I click this, I am red</p>
<p class="black_to_red" onclick="get_red(this)">If I click this, I am red</p>

Better practice is to bind the click event handler using code, and not use onclick attributes. In that case this will refer to the element that got the click event:

function get_red() {
    this.style.color = 'red';
}
document.querySelectorAll(".black_to_red").forEach(function (elem) {
    elem.addEventListener("click", get_red);
});
<p class="black_to_red">If I click this, I am red</p>
<p class="black_to_red">If I click this, I am red</p>

Solution 2:[2]

Passing the current DOM element has parameter will do what you want.

Change you HTML to

<p class="black_to_red" onclick="get_red(this)">If I click this, I am red</p>

And the function to

function get_red(element) {
    element.style.color = 'red';
}

Obs: It is always preferable to use listeners instead of onclick

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 trincot
Solution 2 Nero