skip to Main Content

i have the following image tag with a class name "kiwi" though i have another class which makes the image spin . i want to toggle this class (called ‘elem’) when i click on the play button of my music player

this is the image tage with the class

<img src="./images/kiwi.png" class="kiwi" aria-hidden="true" />

i want to do

<img src="./images/kiwi.png" class="kiwi **elem**" aria-hidden="true" /> 

and this is the play button which should add ‘elem’ class to the image tag onced clicked

<button onclick="justplay()" id="play"><i class="fa fa-play" aria-hidden="true"></i></button>

here is the script for play button

let play = document.querySelector("#play");

function playsong() {
    track.play();
    Playing_song = true;
    play.innerHTML = '<i class="fa fa-pause" aria-hidden="true"></i>';
}

I want the round image to spin when play button is pressed

I tried googling this but i could not figure it out with classList

2

Answers


  1. To add a class to an element, do this:

    element.classList.add('elem')
    

    Further reading about the classList property.

    Login or Signup to reply.
  2. its for one element:

    let el = document.querySelector('.kiwi')
    
    el.addEventListener('click', (e) => {
            e.target.classList.toggle('elem')
        })
    .elem{
      border:1px solid red;
    }
      <ul>
          <li class="kiwi">1</li>
      </ul>

    if you have more .kiwi you need to querySelectorAll and use forEach to add eventListener like THIS:

    let el = document.querySelectorAll('.kiwi')
    
    el.forEach((item, index) => {item.addEventListener('click', (e) => {
            el.forEach((toRemove) => {
                toRemove.classList.remove('elem')
            })
            e.target.classList.toggle('elem')
        })
    })
    .elem{
      border:1px solid red;
    }
      <ul>
          <li class="kiwi">1</li>
          <li class="kiwi">2</li>
          <li class="kiwi">3</li>
      </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search