Add or remove an ID from the swatch gallery based on its presence or absence

I'm currently working on a handleClick function for a gradient swatch gallery. The goal is to add an id of "bg-gradient" to the clicked element, and if another swatch is clicked, remove that id from the previously clicked swatch and add it to the newly clicked one. Essentially, only one element should have the id"bg-gradient" at any given time. Although my code is close to working, it currently adds the id to every clicked swatch, which is not the desired behavior. I believe this issue should be relatively simple to resolve, but I'm struggling to make it work. Please see the code snippet below and the attached screenshot showing the problem (all 4 swatches getting the id).

handleSwatch(){
    let el = document.querySelectorAll('.swatch');
    for(let i=0; i < el.length; i++) {
    el[i].addEventListener('click', function () {
      if (!document.querySelector("swatch#bg-gradient")) {
      el[i].setAttribute('id', 'gradient');
    } else {
        alert('Element exists!');
    }
      });
    }
   }
 }

[![Remove first (or set if not exist), add new id to clicked element][1]][1]

Thanks

Answer №1

If you need a solution, consider implementing the following code snippet:

const swatches = document.querySelectorAll('.swatch');

swatches.forEach(swatch => {
  swatch.addEventListener('click', () => {
    const gradientSwatches = document.querySelectorAll('.swatch#bg-gradient');
    
    gradientSwatches.forEach(gradientSwatch => gradientSwatch.removeAttribute('id'));
    
    swatch.setAttribute('id', 'bg-gradient');
  });
});

To see this code in action, visit this link.

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

Storing property data outside of the render method in ReactJS is key for efficient

I have encountered an issue while attempting to map data outside of the render method in my function and return it within the render. The mapping error is causing confusion as I am uncertain about its underlying cause. Below is the function responsible fo ...

What is the fallback mechanism in Astro js when the cache is unavailable?

When the cache is not accessible in Next.js, the page will be server-side rendered and displayed using either the true or blocking fallback approach. I am curious about the approach taken by Astro.js in this situation. I am planning to develop a dynamic b ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

Trigger .gif on hover using ng-repeat in AngularJS

Many solutions to this problem involve using jQuery, such as the following examples: Stop a gif animation onload, on mouseover start the activation and Animating a gif on hover. However, I'm interested in achieving the same functionality using Angular ...

Can Mongoose handle document arrays editing and version control efficiently?

Currently working on a web application using Node.js and MongoDB/Mongoose, the main model in our project is Record which contains numerous subdocument arrays such as "Comment", "Bookings", and "Subscribers". However, when users click the delete button in ...

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...

Tips for extracting information from a website with Selenium using Python

I am currently working on a project that requires me to extract certain information using Selenium from a webpage. The elements I need are not directly visible in the page's code, indicating they may be generated by JavaScript. Here is a snippet of my ...

Error: Unable to locate module '@/components/Header' in Next.js project

I'm currently facing an issue while working on my Next.js project. The problem arises when I attempt to import a component into my 'page.js' file. In the 'src' folder, I have a subdirectory named 'components' which contai ...

Choosing several checkboxes and populating an array with values - HTML and JavaScript

I am working on a modal dialog that displays a table with checkboxes next to user names. My goal is to link these checkboxes to the respective names so that when a box is checked next to 'Jon' in the table, the name 'Jon' gets selected. ...

Tips for assigning information from a react hook within a function or event

Currently, I am in the process of learning how to create hooks in order to efficiently reuse data that needs to be modified across different components. For my project, I am utilizing Material UI's Tabs and require the use of a custom hook called use ...

It's important to understand how to correctly send state values from a parent component to a child component

I have a tab menu in my code and I am looking to implement a feature where tabs can be switched using a button. The challenge is passing the values of these tabs into the onclick function of the button in order to navigate between them. Here is an example ...

Tips on how to update a table following each button click during an ajax request

I am encountering an issue while trying to display data in a table by clicking on a search button. The problem arises when there is no data between the specified "Fromdate - Todate" range; the error message appears correctly. However, even after entering t ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

The React application is being continuously accessed by a node.js server and processed within async functions

Currently, I am utilizing React, MongoDB, Node.js, and Express in my project. The specific scenario I am facing involves the following code snippet within my component: renderWishlist(){ var quantity; var itemID; var tmp; var my ...

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...

Unable to modify page property status through the Notion API

I've been attempting to use the Notion JS-sdk to update a page's status using their API. However, I've run into some issues that I can't seem to resolve. Updating the status requires modifying the properties object, but no matter what ...

Is there a way to cycle through an array with each click?

I am currently working on implementing a slider feature that enables users to navigate through different pieces of information by clicking on arrows. However, I have encountered an issue where one arrow works correctly (forward), but the other arrow does n ...

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...