0

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?

Haider
  • 81
  • 7

2 Answers2

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>
trincot
  • 317,000
  • 35
  • 244
  • 286
1

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

Nero
  • 51
  • 4
  • Hi Nero! Thanks for your answer. I have never been hearing from so called listeners. Could you maybe tell me why it would be better to use them? – Haider Mar 30 '22 at 18:26
  • See the notes at https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener. – isherwood Mar 31 '22 at 14:23