jQuery: Remove the class if it exists, and then assign it to a different element. The power of jQuery

Currently, I am working on a video section that is designed in an accordion style. My main goal right now is to check if a class exists when a user clicks on a specific element. The requirement for this project is to allow only one section to be open at a time.

  1. Check if the class exists upon clicking
  2. If it does exist, remove the class
  3. Add the class to the clicked element

I have attempted to achieve this functionality using both the addClass(); and toggleClass(); methods, but I am not entirely certain what I may be overlooking.

Adding a Class

$(".contents-row").click(function(){
    $(this).toggleClass("content-open");
}); 

Toggling a Class

$('.contents-row').click(function(){
    $(this).toggleClass('content-open');
});

Here is the basic HTML structure:

<div class="contents-row">
    <div class="content-option press">
        <div class="class-section-title">test1</div>
    </div>
    <div class="drop">
        test 1
    </div>
</div>

You can view a complete version of the drop-down feature on JSFiddle.

Thank you for your assistance!

Answer №1

To start, eliminate the content-open class from all elements that currently have it. Next, incorporate the class into the element that was clicked on as shown in the code snippet below.

$('.row-of-contents').click(function(){
    $('.content-open').removeClass('content-open');
    $(this).addClass('content-open');
});

Answer №2

To start, the class content-open must be removed from every div that has the class contents-row. Afterward, it should be added to the specific div that was clicked.

$('.contents-row').click(function(){
    $('.contents-row').removeClass('content-open');
    $(this).toggleClass('content-open');
});

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

Mobile.changePage does not trigger the pageinit event in jQuery Mobile

I've encountered an issue with handling the on-click event of a button in the following code snippet: $(document).on("click", '.submit_review_button', function(event, ui) { var place = $.data(this, "object"); var ttext = $("#revie ...

Conceal overflow content within a Bootstrap btn-group using CSS styling

Suppose I have a table like the one below: /* CSS Styles for the table */ table.my { width: 600px; } table.my > tr { height: 40px; overflow: hidden; } .tag { background: #b8b8b8; padding ...

What is the best way to align a single item to the right on the navbar in Bootstrap 5.3 (v5.3.0-alpha1)?

Attempting to position a dropdown link to the right in my Bootstrap 5.3 navbar proved to be challenging. The method that worked with Bootstrap 3, using navbar-right, and with Bootstrap 4, possibly ml-auto, did not work with Bootstrap 5 beta which uses me-a ...

Difference between ng-controller variable and ng-init variable

When working with the code snippet below in angularJS, <script type="text/javascript"> angular.module('app').controller('add', ['$scope',function($scope) { $scope.name = "Bonita Ln"; }]); </script& ...

Does ajax rely on jquery for functionality?

I've done some research on this topic, but I haven't been able to find much information. If someone could provide more details, it would be greatly appreciated. Thank you in advance for any assistance. ...

Is there a way for me to personalize the background of the mui-material datagrid header?

I am looking to update the background design of Mui Datagrid from this image to this image However, I am encountering an issue where the background color does not fully cover the header. I have attempted using "cellClassName:" in the columns but it has n ...

Issue with AJAX POST request: PHP failing to establish session

I would like to pass the element's id to PHP and create a session for it. This snippet is from a PHP file: <?php $sql = "SELECT id FROM products"; $result = mysqli_query($con,$sql); while($row = mysqli_fetch_array($result)) { ?> <tr cl ...

Error: Trying to access the 'keyboard' property of an undefined object

I am encountering an error message 'Cannot read property 'keyboard' of undefined' and I'm not sure how to fix it. I just want to check if the keyboard is visible on the screen, but this specific line of code seems to be causing the ...

What methods are available for retrieving specific XML entries using JavaScript?

Hey there, I'm dealing with this XML code <book> <bookname>book1</bookname> <author>authorman</author> </book> <book> <bookname>book2</bookname> <author>authorperson</author> </book ...

When incorporating babel-plugin-styled-components, Nextjs may encounter a mismatch error with classnames

After transferring the content of _document.js from the following styled components example and implementing the babel plugin mentioned in the styled components documentation, I am still encountering an error. _document.js import Document from 'next/ ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Next up: Changing Traffic Signal Operations

In my project to manage traffic signals, I am faced with the challenge of coordinating four roads, each with its own traffic light. Currently, I have successfully implemented the traffic light for a single road, but I am struggling to make it switch to the ...

Tips for simultaneously displaying and updating HTML content

I have a hidden bootstrap alert div that is meant to display errors. I am trying to simultaneously show the alert and change its HTML content using jQuery. I attempted the following code snippet, but it does not seem to be working as intended. var erro ...

Facing an "error: JSON object access not defined" issue? Read on to find

$(document).ready(function() { var output = "<div>"; $.getJSON('https://search-a.akamaihd.net/typeahead/suggest/?solrformat=true&rows=20&callback=noCB&q=*%3A*+AND+schoolid_s%3A1255&defType=edismax&qf=teacherfirstna ...

The OutlinedInput component from Material-UI seems to be struggling to display the startAdornment

Below is the code snippet. The start adornment is not displaying in the textfield, and there is no text appearing on the label. <InputLabel>Mobile Number</InputLabel> <OutlinedInput variant="outlined" ...

I'm currently in the process of creating a snake game using HTML5. Can you help me identify any issues or problems that

I am experiencing an issue where nothing is appearing on the screen. Below are the contents of my index.html file: <html> <body> <canvas id="canvas" width="480" height="480" style="background-color:grey;"></canvas> <script src=" ...

What is preventing me from installing react-router-transition on the 1.4.0 version?

$ npm install -S <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dffe8eceef9a0ffe2f8f9e8ffa0f9ffece3fee4f9e4e2e3cdbca3b9a3bd">[email protected]</a> npm ERROR! code ERESOLVE npm ERROR! Unable to r ...

Display all elements that come before and after the current element

For debugging purposes, I need to output the IDs of all previous images in a check. The issue arises when trying to assign classes to all previous elements using the script below, as the images are not being added to the correct classes. $(document).on(&a ...

Divide a single array into two separate arrays using React Native

My goal is to divide an array into two separate arrays, one for letters and the other for frequencies. var list = [ "ES 324798", "LE 237076", "EN 231193" ] This is the original array that needs to be split. I am looking to create an array with all the l ...

HTML - Is there a way to hide the label showing the number of files selected when using input type=file?

I am seeking a way to either eliminate the label that indicates the number of selected files, or be able to control it so that when I upload a file, the label increases and decreases when I delete an uploaded file. How can I achieve this? Below is my HTML ...