October 22, 2024
Chicago 12, Melborne City, USA
javascript

Can you assign an elements class list to a variable by clicking on the element?


The main question I have is: Is there a way to assign to a variable an elements class list by clicking on said element.

Expanding on this, I’m trying to create a function that – on clicking an image in a photo grid – expands the image making it clearer for people to see. I made a for loop that loops through an array that contains the class lists of all images in the grid, the idea was that upon clicking on any one of the images a function that contains the loop would be called and the class list for the image that was clicked would be stored as a variable, the loop would then compare each value in the array to the variable and upon a match would apply a class that enlarges that particular image, this way I could use one function for every image in the grid instead of writing 15+ functions where each one was called depending on the image clicked. I’ve run into an issue when trying to retrieve the class list for the image that was clicked on – that being I can’t figure out how to retrieve the class list for an element by clicking on said element.

As I said I could just make 15+ different functions each with a variable directly assigning that specific images class but that hardly seems like the best way to do this. If this just isn’t possible also let me know please.

My JS as it stands:

function enlarge() {
    let figureArray = [] = document.querySelectorAll(".photo-grid figure");
    let figure = ; //This is where the class list of the clicked element would be stored
    for (let i = 0; i < figureArray.length; i++ ) {
        if (figureArray[i] === figure) {
            figureArray.item(i).classList.toggle("zoom"); 
        }
    }
};



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video