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

104
Views
toggle Span class with button in a loop

So I'm playing around with Font Awesome and BootStrap, and I'm looking for a way to toggle my star icon on the button. Problem is, it's inside a loop.

{% for i in X %}
    <button id="{{i.id}}"><span class="class1" id="StarIcon"></span></button>
{% endfor %}

I want to change the respective span from 'class1' to 'class2' upon click, however just knowing how to change all of them or even just the last one would already be of help.

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

0

You can use classList.add() and classList.remove():

const el = document.getElementById('someButton');

document.getElementById('{{i.id}}').onclick = () => {
  el.classList.add('class2');
  el.classList.remove('class1')
}
<button id="{{i.id}}"><i id="someButton" class="class1" id="StarIcon">Button!</i></button>

about 4 years ago · Juan Pablo Isaza Report

0

Not sure if I understtod you right, but probably you're looking for something like this:

{% for i in X %}
    <button id="{{i.id}}"><span class="class1" id="StarIcon"  onclick="btnClick(this)"></span></button>
{% endfor %}

...

function btnClick(el) {
    const spanEl = el.querySelector('#StarIcon');
    if (spanEl.classList.contains('class1')) {
        setClass2(spanEl);
    } else if (spanEl.classList.contains('class2')) {
        setClass1(spanEl);
    }
}
function setClass1(el) {
    el.classList.add('class1');
    el.classList.remove('class2');
}
function setClass2(el) {
    el.classList.add('class2');
    el.classList.remove('class1');
}
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!