Change the class of the div when the first div is selected

My goal is to switch the class of the #klapp element (from .klapp to .klappe) whenever a click event happens inside the #label-it container, including when the #klapp element itself is clicked. The challenge is that I am not able to use unique IDs for each element.

$('#label-it').click(function() {
  $(this).next(".filter-panel").toggleClass('klapp');
  $(this).next(".filter-panel").toggleClass('klappe');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>
<div id="label-it" class="label-it">
  <label class="filter-panel">
      <div id="klapp" class="klapp"></div>
   </label>
</div>

Initially, I attempted the following approach, but it only affected the first #klapp element inside the #label-it container:

$('#label-it').click(function(){
  $("#klapp").toggleClass('klapp');
  $("#klapp").toggleClass('klappe');
});

Answer №1

There are a couple of issues that need to be addressed in this code snippet. Firstly, the id attributes are repeated on multiple elements, which is not valid HTML. It is recommended to remove these id attributes and utilize the existing class attributes instead.

Secondly, the use of next() is incorrect in this context as .filter-panel is a child of .label-it. The correct method to use in this scenario is find(). Additionally, it is important to select the div element within .filter-panel as it contains the .klapp class. The updated code snippet is as follows:

$('.label-it').click(function() {
  $(this).find(".filter-panel div").toggleClass('klapp klappe');
});
.klapp {
  color: #CCC;
}

.klappe {
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">A</div>
  </label>
</div>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">B</div>
  </label>
</div>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">C</div>
  </label>
</div>
<div class="label-it">
  <label class="filter-panel">
    <div class="klapp">D</div>
  </label>
</div>

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

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

Getting Started with Material UI's Default Components

After working with bootstrap, I decided to explore the material ui framework as well. However, when trying to use the default MUI component without customization, such as the card component, I encountered some difficulties. Here is an example of one of th ...

jQuery and Easy Dialog

My jQuery Model window has a form inside. Even though I have set autoOpen to false in my dialog, the fields are still visible when the page is created. All forms are contained within a div. This is what my dialog code looks like: $("#dialog-form").dial ...

Removing numerous items with checkboxes

Currently, I am working on enhancing my shopping list functionality. I have successfully implemented a feature to delete individual items from the list. However, I am facing difficulty in deleting multiple items using checkboxes. The structure of my item t ...

What is the most efficient way to optimize the time complexity of a JSON structure?

Here is the input JSON: const data = { "38931": [{ "userT": "z", "personId": 13424, "user": { "id": 38931, "email": "sample", }, } ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

Error in HTML5 video: Unable to access property '0' as it is undefined

I am trying to create a simple block displaying an HTML5 video tag. I want the ability to play different videos along with their titles from a JSON file by using previous and next buttons. Clicking the next button should play the next video, and the same g ...

Bootstrap is unable to function properly without jQuery, throwing an error message that states: "Bootstrap's JavaScript

Attempting to create a Bootstrap interface for a program. Added jQuery 1.11.0 to the <head> tag, however upon launching the web page in a browser, jQuery throws an error: Uncaught Error: Bootstrap's JavaScript requires jQuery Various attempts ...

What is the process of transferring data from one div to another div (table) using AngularJS?

In my quest to enhance my table with JSON data upon clicking the + icon, I am faced with two sections: Pick Stocks where stock names and prices (retrieved from data.json) need to be added to the table found in the Manage Portfolio section. First Section h ...

Patience is key as you await the element to load and smoothly render the data in vue.JS

Is there a way to ensure that the graph is only rendered and filled with data after the data has been returned from the backend? Currently, even though the data is returned, the graph appears blank. Here is my JavaScript code: methods: { refresh( ...

Encountered Node.js & MySQL error: 1251 - Client not able to support authentication protocol requested by server. It is recommended to upgrade MySQL client for resolving this

I currently only have the following code snippet: const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'root', 'passwd', { host: 'localhost', dialect: 'mysql', ...

Only the data from the first row will be accepted by jQuery, no other data will be

Encountering a problem with jquery. I have a dynamically created <table>. foreach ($_cards as $_card){ $tabOdd = ""; $statusInd = ""; $counter++; if ($counter % 2 != 0){ $tabOdd = "style='background-color:#eee' ...

Ensure that my program is halted until the xmlhttprequest has completed

It seems like I've overcomplicated this problem for myself. In my page, I have 2 XMLHTTPRequests - the first request retrieves data from an API and fills my elements with this data. However, one of the fields in my elements requires a second request t ...

Tips for implementing a switch-case statement with variable formats that may not always be

switch (req.path) { case "/api/posts": console.log("posts"); break; case "/api/posts/tags/*": // the part * is always changing depending on user input console.log("tags"); break; case "/api/best": console.log ...

Embed the json data within the modal box

I received a JSON response from a php function, and it looks like this: [{"id":"15","activity_type":"call","activity_title":"Call to check "}] Below is the script that triggers the request (actvitiy.js) (Edited) $(document).on("click", ".view_contact_ac ...

What is the process for including icons on buttons?

I have been researching how to use Font Awesome software to incorporate icons into my HTML elements, but I am uncertain about the implementation process for my specific case. Currently, I have created a basic webpage with buttons and I would like to includ ...

Excess space located adjacent to primary content on website

When you scroll to the left of the page, next to the main content and outside of the browser width, there is additional space occupied only by the background of the Body CSS. Take a look at the site in action: . @charset "utf-8"; /* Custom CSS Styles * ...

Storing information using ajax and json technologies

I've inherited a project where I need to work on saving data to the database using an input. The function responsible for this (SaveData) is not functioning properly. Since I'm not very familiar with ajax and json, can someone please help me iden ...

ChooseMe date selector - eliminated the preset current date

I have implemented the PickMeUp multi date picker and here is my jQuery code. $('.multiple').pickmeup({ position : 'top', hide_on_select : false, mode : 'multiple' }); Currently, the calend ...

Use jQuery to refresh the jQuery sparkline chart after fetching data asynchronously

Background Utilizing the jquery.sparkline library to generate Pie Charts. The data for these charts is stored in an array. Upon initial page load, a web-service call is made (using .ajax) to fetch the data. The callback function associated with this call ...