Guide on altering the Class with jquery

Here is My jQuery Code:

   $('a#cusine1').on('click', function(){  
        $('div#product-list').html("LOADING..........").show();  

        $(".ccid").addClass("0");
        document.getElementById("ccid1").className="active2";     

    });  


        $('a#cusine2').on('click', function(){  
        $('div#product-list').html("LOADING..........").show();  
        $(".ccid").addClass("0");
        document.getElementById("ccid2").className="active2";

    });  


        $('a#cusine3').on('click', function(){  
        $('div#product-list').html("LOADING..........").show();  
        $(".ccid").addClass("");
        document.getElementById("ccid3").className="active2";

    });  

This is the HTML CODE I'm Using:

      <li id="ccid1" class="ccid">
             <a href="#" id="cusine1"><i class="fa fa-ticket"></i>3 Star Hotel</a>                                  </li>
        <li id="ccid2" class="ccid">
              <a href="#" id="cusine2"><i class="fa fa-ticket"></i>3 Star Hotel</a>                            </li>
        <li id="ccid3" class="ccid">
   <a href="#" id= "cusine3"><i class="fa fa-ticket"></i>5 Star Hotel</a>
     </li>

The Desired Output Should Be:

When li with the id "ccid1" is clicked, the class "active2" should be added. All other li elements should only have the "ccid" class.

The number of li items may vary depending on PHP.

An Issue Found:

Upon the first click on the li item with the id "ccid1", the class "active2" is successfully added. However, if then clicking on the li element with the id "ccid2", the class "active2" gets added, but the li with the id "ccid1" does not get set to "0".

Answer №1

In the world of CSS, it's important to remember that class names cannot begin with a number (CSS grammar). Additionally, any HTML element has the ability to have multiple classes assigned to it. If you find yourself in a situation where you need to delete a class (or set it to none), the best method to use is removeClass.

Answer №2

In my previous response, I mentioned that it's best to avoid using classNames that start with a forward slash followed by only numbers.

Here is the updated code snippet that should meet your needs:

$('.ccid a').on('click', function(){              // Targeting all links with class ccid
    $('div#product-list').html("LOADING..........").show();  
    $(".active2").removeClass("active2");         // Remove any existing active classes
    $(this).parent(".ccid").addClass("active2");  // Add active class to parent element 
});  

Answer №3

It seems like you're looking for a solution, so I'll take a shot at it without testing the code:

$('li.ccid').on('click', function(){  
    $(".ccid").removeClass("active2");
    $(this).addClass("active2");
});

Basically, whenever a list item with the ccid class is clicked:

  1. We make sure to remove the "active2" class from all other similar list items
  2. The "active2" class is then added to the one that was clicked on

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

How to style a sublevel menu to appear next to its parent using CSS

I have a menu that is currently functioning well, but I would like to add a new sublevel onto it. However, if I directly add the new options, they end up hiding the existing ones on the menu. Here's an image for reference: I want the new options to ...

employ identical components in v-if and v-else

Currently, I am in the process of designing a login/register page using Vue. The layout includes separate tabs for both login and registration purposes. Here is a snippet of my template code: <transition v-bind:name="TabEffect"> <div ...

"Interactive jQuery feature allows users to edit table content live with the ability to update and delete data via

I am working on implementing live editing, updating, and deleting functionality in a table using jQuery. However, I have encountered two problems: When clicking the pen icon from order #3 to #1, it requires 3 clicks, but when clicking from order #1 to ...

"Setting up a filter for the first row in an Excel-like table using a pin header

Does anyone know how to create a table filter in Excel where the header and first row stay pinned while scrolling down, even after applying filters? Here is a JSFiddle demonstrating the issue: http://jsfiddle.net/6ng3bz5c/1/ I have attempted the followi ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

Switching between different sections of a webpage

Seeking assistance with implementing a transition effect between sections on a single-page application. All sections are located on the same page, but only one section is displayed at a time. When an event occurs, the display property of the requested sect ...

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...

Attempting to hash the password led to encountering an error

An issue was encountered: both data and salt arguments are required. This error occurred at line 137 in the bcrypt.js file within the node_modules directory. The code snippet below highlights where the problem is present: const router = require("express" ...

Unsuccessful response from an AJAX callback function

Issue: I am able to successfully pass a value to the ajax method and execute a Select SQL query (results visible in Network tab), but I never receive any results back (I expect an alert saying "Success"). What could be causing this issue? HTML: function ...

Does anyone know if it's achievable to include a background position within the img /asp:image tag?

Currently, I am endeavoring to enhance the loading speed of my webpage. The initial approach I decided to pursue is base64 conversion. On my homepage, there are a total of 18 small images that need to be loaded. Since base64 encoding increases image size ...

Http post request failing to execute

I'm having an issue with an ActionResult that has the HttpPost attribute. It seems like I need this attribute when the user selects a date from a DateTimePicker. In my scenario, I have 2 DateTimepickers of type @html.EditorFor. These pickers correspon ...

Unusual behavior observed with Chrome image resizing

I've encountered an odd issue with Chrome related to image resizing when the window size changes. When I have Chrome snapped fullscreen in Windows (double-clicking to snap), and then unsnap the window, the images are not scaling correctly back to the ...

Looking for a way to add a permanent footer to the bottom of your webpage without affecting the tab order for accessibility?

I have a paginated form with a fixed navigation footer at the bottom that needs to stay in place even when scrolling. This footer should also be at the bottom of the page for mobile devices and tablets. To achieve this, I used position: fixed on the foote ...

The text in Outlook for Windows emails is being obscured by a button that is overlapping it

As a newcomer to HTML email development, I've encountered an issue that has been puzzling me for the past few days. The problem lies in creating a two-column layout where the left column contains an image and the right column holds text along with a b ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

Check off all checkboxes and send their values to an AJAX script using a table

I currently have a table set up with checkboxes in the first column. By checking these boxes, an AJAX script is triggered that updates a PHP session variable with the selected values. This functionality is working smoothly. However, I am now looking to enh ...

What could be causing the lack of value appearing after I clicked the button?

Setting the value for the array of images as an empty string does not return the expected result. When I move one of the 4 images and click the button, I anticipate a new array with the information of one of the four images including src, x, and y coordina ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...

Attempting to access a variable from outside the function

I am looking to pass the index variable from mapping to the event change function in my code snippet below: {this.data && this.data.map((item, index) => ( <tr className="table-info" key={index}> <td>{index}</ ...

Is there a way to display a React component containing an array that is constantly changing due to an external function?

I am facing a challenge involving a component that needs to render an array of divs. The requirement is to add another div after a certain external function is triggered. This function must be declared outside the component for export purposes. The issue ...