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

131
Views
Javascript Toggle a class on clicked class element

Bit of a basic one, I was unable to to find exactly what I was after on Stack/Google..

Using vanilla javascript, I'm looking to simply toggle a class on the below .barBtn elements, specifically the one I click.

Sample JS Fiddle: https://jsfiddle.net/t376kL4q/

<div class="container">
    <div class="btnBar">
        <div class="barBtn">Wishlist</div>
        <div class="barBtn">Collection</div>
        <div class="barBtn">Info</div>
    </div>
</div>

<div class="container">
    <div class="btnBar">
        <div class="barBtn">Wishlist</div>
        <div class="barBtn">Collection</div>
        <div class="barBtn">Info</div>
    </div>
</div>

I have tried adapting others' code found on Stack/Google, e.g. this one which I've JSFiddle'd: https://jsfiddle.net/5rmqucj3/

Where I changed

document.getElementById("mytarget").

to

document.GetElementsByClassName("mytrigger").

(or even 'querySelector')... but I'm not sure how to correctly target the specific class element I click.


Whether or not the above (2nd link) is the best way to go about the JS of this I'm not sure, but generally just after a clean/simple way of achieving this.

Any help would be much appreciated.

Thanks

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You need this

var navclick = document.getElementsByClassName("mytrigger");
for (var i = 0; i < navclick.length; i++) {
  navclick[i].onclick = function(e) {
    this.classList.toggle('myactive');
  }
}
.myactive {
  background-color: blue;
  color: white;
}
<button class="mytrigger">Button
    </button>

<div id="mytarget">
  <p>Hello</p>
</div>

<button class="mytrigger">Button
    </button>

about 4 years ago · Santiago Gelvez 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!