简体   繁体   中英

jQuery replace one class with another

I have this jQuery and I'm changing styles in it but I've heard that the correct way to do it is to create a separate style and just replace classes with jQuery. Can you explain me how to do it correctly:

$('.corpo_buttons_asia').click(function() {           
    $('.info').css('visibility', 'hidden');
    $('.info2').css('visibility', 'visible');
    $(this).css('z-index', '20');
    $(this).css('background-color', 'rgb(23,55,94)');
    $(this).css('color', '#FFF');
    $('.corpo_buttons_global').css('background-color', 'rgb(197,197,197)');
    $('.corpo_buttons_global').css('color', '#383838');         
}); 

$('.corpo_buttons_global').click(function() { 
    $('.info').css('visibility', 'visible');
    $('.info2').css('visibility', 'hidden');
    $(this).css('background-color', 'rgb(23,55,94)');
    $(this).css('color', '#FFF');
    $('.corpo_buttons_asia').css('z-index', '2');
    $('.corpo_buttons_asia').css('background-color', 'rgb(197,197,197)');
    $('.corpo_buttons_asia').css('color', '#383838');
}); 


So instead of using .css() all the time I can create another class and just replace it with jQuery.

To do this efficiently using jQuery, you can chain it like so:

$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');

For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow') ):

var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');

Also (since there is a js tag), if you wanted to do it in vanilla js:

For modern browsers ( See this to see which browsers I'm calling modern )

(assuming one element with class theClassThatsThereNow )

var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');

Or older browsers:

var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');

You may use this simple plugin:

(function ($) {
    $.fn.replaceClass = function (pFromClass, pToClass) {
        return this.removeClass(pFromClass).addClass(pToClass);
    };
}(jQuery));

Usage:

$('.divFoo').replaceClass('colored','blackAndWhite');

Before:

<div class="divFoo colored"></div>

After:

<div class="divFoo blackAndWhite"></div>

Note: you may use various space separated classes.

Starting with the HTML fragment:

<div class='helpTop ...

use the javaScript fragment:

$(...).toggleClass('helpTop').toggleClass('helpBottom');

有时,当您有多个类并且确实需要覆盖所有类时,最简单的方法是使用 jQuery 的.attr()覆盖class属性:

$('#myElement').attr('class', 'new-class1 new-class2 new-class3');

在 jquery 中用另一个类替换一个类,您可以使用jqueryUI SwitchClass选项

 $("#YourID").switchClass("old-class-here", "new-class-here"); 

You'd need to create a class with CSS -

.greenclass {color:green;}

Then you could add that to elements with

$('selector').addClass("greenclass");

and remove it with -

$('selector').removeClass("greenclass");

You can use .removeClass and .addClass . More in http://api.jquery.com .

You can use jQuery methods .hasClass() , .addClass() , and .removeClass() to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.

jQuery.fn.replaceClass = function(sSearch, sReplace) {
    return this.each(function() {
        var s = (' ' + this.className + ' ').replace(
            ' ' + sSearch.trim() + ' ',
            ' ' + sReplace.trim() + ' '
        );
        this.className = s.substr(1, s.length - 2);
    });
};

EDIT

This is my solution to replace one class with another (the jQuery way). Actually the other answers don't replace one class with another but add one class and remove another which technically is not the same at all.

Here is an example:

Markup before: <br class="el search-replace"><br class="el dont-search-replace">
js: jQuery('.el').remove('search-replace').add('replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace replaced">


With my solution

js: jQuery('.el').replaceClass('search-replace', 'replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace">


Imagine a string replace function in whatever language:

Search: "search-replace"
Replace: "replaced"
Subject: "dont-search-replace"
Result: "dont-search-replace"
Result ( wrong but actually what the other solutions produce): "dont-search-replace replaced"


PS If it's for sure that the class to add is not present and the class to remove is present for sure the most simple jQuery solution would be:
jQuery('el').toggleClass('is-present-will-be-removed is-not-present-will-be-added')

PPS I'm totally aware that if your selector equals the class to remove the other solutions would work just fine jQuery('.search-replace').removeClass('search-replace').addClass('whatever') .
But sometimes you work with more arbitrary collections.

Create a class in your CSS file:

.active {
  z-index: 20;
  background: rgb(23,55,94)
  color: #fff;
}

Then in your jQuery

$(this).addClass("active");

你可以让他们都使用“corpo_button”类或类似的东西,然后在$(".corpo_button").click(...)调用$(this).toggleClass("corpo_buttons_asia corpo_buttons_global");

I have used swap div to swap my video of self in thumbnail to main-video and vise versa.

I think this will help you to make a toggle between two div class.

numberId=0
function swapVideo(){
  numberId++;
 console.log(numberId)
  if(numberId % 2 ==0){
  $('#self-video').attr('class', 'main-video');
    $('#trainer-video').attr('class', 'thumb-video');
  }else{
     $('#self-video').attr('class', 'thumb-video');
         $('#trainer-video').attr('class', 'main-video');
  }
}

numberId%2==0 help to keep track and perform a operation to make this toggle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM