Is it possible to exchange CSS classes for a specific group of elements using JQuery?

I have two list items listed below:

<li name="luxury" class="cars luxury>                                           
    <div id="featured_lux" name="featured" class="carImg_lux col2_lux ">
        My Luxury Car<img border="0" class="car-image_lux" src="/images/toycar_luxury.gif">
    </div>

    <div class="brandName_lux col2_lux">
        <h2 class="showBig_lux">
            Ferrari or Ford Mustang
        </h2> 

    </div>          

</li>

AND this

<li name="normal" class="cars normal>
    <div id="featured_normal" name="normal" class="carImg_normal col2_normal ">
        My Normal Car<img border="0" class="car-image_lux" src="/images/toycar_normal.gif">
    </div>

    <div class="brandName_normal col2_normal">
        <h2 class="showBig_normal">
            Alto or Innova
        </h2> 

    </div>          

</li>

Both sections look similar. The only difference is their CSS class and content.

Is there a way to easily swap the CSS classes for both sets of elements using jQuery? For example, applying the Luxury CSS class to the Normal Car Section and vice versa.

I know I can do this using addClass() and removeClass() in jQuery. But is there a more direct approach with minimal lines of code?

This change should occur by default based on some condition, without requiring any clicking or hovering.

I prefer not to use any external libraries if possible.

Please help. Thank you :)

Answer №1

If you want to toggle classes, you can use the toggleClass method.

$(function() {
    $('.swap').click(function() {
        $('.a, .b').toggleClass('a b');
    });
});
                    
.a { background: red; }
.b { background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script>
<div class="a">#</div>
<div class="b">#</div>
<input type="button" class="swap" value="Swap Classes" />

To swap classes by passing them to a function, you can do the following:

$(function() {
    swapClasses('red', 'blue');
    function swapClasses(a, b) {
        $('.' + a + ', ' + '.' + b).toggleClass(a + ' ' + b);
    }
});
body {
    color: white;
    font-weight: bold;
}
div {
    padding: 4px;
    margin: 4px;
}
.red { background: red; }
.blue { background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script>
<div class="red">RED</div>
<div class="blue">BLUE</div>

Check out the fiddle here: https://jsfiddle.net/z2ogcs3x/

Answer №2

If you prefer to use plain vanilla code instead of jQuery, you can visit a helpful site called You Might Not Need jQuery. This site showcases jQuery methods alongside their vanilla JavaScript alternatives.

For instance:

Instead of using jQuery code like this:

$(el).addClass(className);

You can achieve the same result with vanilla JavaScript like this:

if (el.classList)
  el.classList.add(className);
else
  el.className += ' ' + className;

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 can a JavaScript file interact with a backend without needing to specify the URL in the compiled code, thanks to webpack?

Currently, I am working on a React application with webpack. After compiling the code using the command webpack --mode production && webpack --config webpack.config.prod.js I utilize a .env.prod file to specify the variable REACT_APP_BASE_URL, wh ...

JavaScript - Two tables shown in parallel

Beginner coder seeking assistance! I am currently working on an application with two user input fields placed adjacent to each other. Clicking parse buttons next to these fields generates two separate tables. However, I need these tables to be displayed si ...

What are some methods for converting data from data tables into alternative formats?

I need assistance exporting data from data tables in various formats such as Copy, CSV, Excel, PDF, and Print. Can someone show me how to do this for the example provided below? <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.4 ...

Designing a personalized look for a property with Styled-System

Styled-System offers various props related to css grid: I have a suggestion for a new prop, gridWrap. My idea is to allow users to adjust the auto-fit value using the gridWrap prop. Here's the base CSS code: grid-template-columns: repeat(auto-fit, mi ...

What is preventing me from using JavaScript to generate labels?

My current project involves creating dynamic input fields to filter products by color. I initially attempted static checkbox inputs for this purpose, which worked fine. Now, I want to achieve the same functionality but dynamically through JavaScript. Inste ...

Utilize Jquery to extract HTML content from an array of links and implement regular expressions

Currently, I am embarking on the journey of developing a Google Chrome extension despite my limited experience in this field. My aim is to create a tool that can identify individuals who have left reviews on Amazon products. Specifically, I am looking to l ...

Converting the stage object to JSON format and incorporating it into an HTML5 environment using

$("#show").click(function(){ var stage = Kinetic.Node.create(json, 'container2'); var ball = new Image(); var cone = new Image(); var tshirt = new Image(); ball.onload = function() { stage.get('.ball').apply ...

Verify for a class that does not exist

I am working on a script that updates the content of a div and increments its value by 1 $(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), }, }); ...

Text alignment below a div with absolute positioning

Presently, my setup looks something like this: <div class="mycol" id="mycanvas" style="z-index: -1; top:150px;left:240px;width:88%; height:80%; position: absolute;background-color:red;"> </div> <div class="testclass"> He ...

Tips for repositioning the window when linking to a different section of a website

As a beginner in HTML and CSS, I am currently working on adding a navigation bar to my one-page website. I want the navigation bar to smoothly guide users to different sections of the page when they click on a link. To achieve this, I am using anchors and ...

The animation loop completes and restarts from the initial keyframe

I have a CSS animation that I want to play through once and then stop at the final keyframe. However, currently it keeps returning to the initial keyframe and stopping there instead of reaching the end. The animation involves a title heading that gradually ...

Ensure that the bootstrap popover remains hidden when clicked outside of it, unless there is an element within the

Currently, I am facing an issue with a Bootstrap popover that contains a text input. My goal is to have the popover hide if the user clicks outside of it, and remain open if any elements inside the popover, like the input field, receive focus. Unfortunate ...

Combining Angular with MVC partial views

What I'm Looking For I require a sequence of interactive screens that progress to the next screen upon button click. Each previous screen should collapse while loading the new screen using a partial view from the MVC backend. My Current Setup Curre ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...

Guide to creating a dynamic dropdown with Ajax in Codeigniter

It feels like the [insertLongNumber]th time someone has asked this question, and despite my research efforts, I'm unable to find a fitting solution. So here it goes. I'm currently tackling a dynamic dropdown conundrum using PHP and AJAX in CodeI ...

Vue.js seems to be leading me down a long and steady path of progress at a snail

I've exhausted all efforts to resolve the file paths for Home and App. I even turned to AI to help me out, but still no luck. Code snippet from main.js in the src folder: import Home from '@views/Home.vue'; // Using alias import App from ...

What are the steps to transition from @zeit/next-sass deprecation?

Is there a way to transition and modify the next.config.js file to switch from using @zeit/next-sass to leveraging Next.js's built-in support for Sass? Check out this link for more information: https://www.npmjs.com/package/@zeit/next-sass const withS ...

What is the best way to showcase a collection of items using a table layout in JavaScript?

I am relatively new to React/JS programming and I'm struggling to understand why my code isn't working correctly. My goal is to create a column with rows based on the items in my Array, but only the header of the table is displaying. After looki ...

Turn only one bracket on the accordion

When clicking on a specific header, I want only one chevron to rotate instead of all the chevrons rotating. I am currently unsure how to specify which chevron should rotate individually. My project is in ASP.NET MVC 5 and I am using razor view to loop th ...

My Ajax request does not seem to function properly when attempting to transfer data to a different

Take a look at the following code snippet: <div class="category" id="<?php echo $cat->term_id; ?>"><?php echo $cat->cat_name; ?> </div> $(".category").click(function(){ var categ = $(this).attr('id&apos ...