Tips for including an additional class in an element

I have an image tag with the "kiwi" class, and another class that makes it spin. I want to toggle this second class (called 'elem') when clicking on the play button of my music player.

Here is the image tag with the class:

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

This is what I want to achieve:

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

And here is the play button which should add the 'elem' class to the image tag once clicked:

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

Below is the script for the 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 the play button is pressed

I tried searching online for a solution using classList but couldn't figure it out.

Answer №1

Here's a solution for handling click events on elements with the class 'kiwi':

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 multiple elements with the class '.kiwi', you can use querySelectorAll and forEach to add event listeners 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>

Answer №2

If you want to include a new class in an element, follow these steps:

element.classList.add('elem')

You can find additional information on the classList feature.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Facing issues with receiving API response through Postman encountering error { }

In my MongoDB database, I have created documents for Families, Users, and Devices (https://i.stack.imgur.com/oeDU0.png). My goal is to retrieve all devices associated with a specific family using the family's Id provided in the HTTP request. For examp ...

Retrieve tag, custom taxonomy, and attachment information using the get_pages function

Currently, I have implemented code that retrieves all pages submitted by the currently logged-in author using the get_pages function. The retrieved result is then passed to Javascript via Ajax. Everything functions as expected, and the correct pages are be ...

Syntax error: Your code encountered an unexpected closing curly brace

Here is the code snippet I am working with: <?php session_start();?> <!DOCTYPE html> <html> <head> <title>Narcis Bet</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css" type="text/css"&g ...

Implementing optimistic updates with React-query mutations

Hello everyone! I'm a newcomer to react-query and I've been experimenting with making an optimistic update using the mutation function. However, I've encountered a problem where I'm unable to retrieve the previous value from the query. ...

Submitting data from a JavaScript frontend to a PHP backend

I've exhausted all options in attempting to resolve this issue. The javascript code is designed to send a list of product IDs to a PHP page. When products are selected, the submit button should activate the submit function. function submit() { ...

Exploring the Lifecycle Methods in ReactJS / Issue Resurfacing in the Code Snippet

I recently started learning ReactJS and discovered the concept of lifecycles. However, I have a question about how componentDidUpdate() works and why it behaves in a certain way. To illustrate this, I am sharing a simple code snippet below that calculates ...

hiding an "input type="file" element by using a button to conceal it

Is it possible to create a button that triggers file upload functionality? I couldn't find any solutions on Google. I've heard it can be done with labels, but I specifically need to use a button for better UX/UI. <button style="position:fixe ...

What is the best way to create a dynamic information page using both V-for and V-if in Vue.js?

Hey everyone, I recently attempted to set up this layout: https://i.sstatic.net/WbcBX.png This company offers a variety of services grouped into different categories, each containing sub-options and specific details. This is how my JSON data is structur ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

Struggling to center a MatIcon within a MatButtonToggle component in an Angular project

I've been struggling to center the MatIcon in the MatButtonToggle, trying multiple methods without success. It may seem like a minor issue, but it's causing quite a bit of trouble for me. Can someone please guide me on how to make this adjustment ...

An issue has been encountered in the following module federation: `TypeError: g.useSyncExternalStore is not a function`

I encountered an error after deploying my next app with module federation: TypeError: g.useSyncExternalStore is not a function The same app works fine as a standalone application when run with yarn dev or yarn start, but it fails when using module federat ...

What is the best way to comprehend this asynchronous exercise with async/await?

Currently, I am working on some exercises related to async/await, and I seem to be stuck on the following problem: The function ​​opA​ should be executed before ​opB​, and ​opB​ should be executed before ​opC​. Arrange the function call ...

Showcasing Items Within JSON Object in Angular

I am dealing with a JSON database that contains nested Objects: { "characters2": [ { "campaign":"Menagerie Coast", "index": 1, "name": "Mark Whithershmitz", "portrait": "assets/pics/markW.jpg", "affiliation": "Kryn Dynast ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

Tips for including multiple directives in a component

Apologies in advance for my lack of clarity in expressing this question, which is why I am seeking assistance rather than finding the solution on my own. My query pertains to loading a component within another one and specifying it in the directive. Below ...

Inverted Scrolling Problem in Firefox

I am facing an issue with a script that inverts mouse movement for horizontal scrolling. It works fine in most browsers except Firefox. I could use some advice on how to troubleshoot this problem! $("body").mousewheel(function(event, delta) { ...

Get the desired text following the second <br> tag using jQuery

I am trying to identify a specific string that comes after the second occurrence of <br> tag and then check if this string contains any numbers. If there are no numbers present, I want an alert to be shown. The code for performing this action is func ...

My Testimonial Slider seems stuck in its current position and won't budge to the left

As an aspiring web designer, I took a template from CodePen and crafted a testimonial slider for my website. To seamlessly merge it with the background, I've been trying to shift the entire testimonial to the left. Despite attempting the float-left p ...

Establishing a connection to a remote Mongo database using Node.js

I have a remote MongoDB server and I am looking to establish a connection with it using Node.js. I was able to successfully connect directly with the Mongo shell, but for some reason, I cannot establish a connection to the MongoDB server in Node.js. The co ...

Can the key in a WeakMap be altered when setting an item within it?

When working with JavaScript, is it possible for setting an item in a WeakMap to change the object used as the key? I'm curious about this because if I were to create a WeakMap, my approach might involve using a Symbol on the key and then utilizing t ...