Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

69
Views
Changing specific element with the same function

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!