Home > Software design >  toggle Span class with button in a loop
toggle Span class with button in a loop

Time:10-31

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.

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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');
}
  • Related