How to Remove an Existing Class Name and Add a New One with Jquery and Cookies

How do I remove an existing class name and add a new one with jQuery and cookies?

Use:

$('.red').removeClass('red').addClass('blue');

Here's the full working code:

$(function() {
$("a").click(function() {
var color = $(this).text();
$("body").removeClass().addClass(color);
return false;
});
});

And now for the cookie part

$(function() {
$("a").click(function() {
var color = $(this).text();
$("body").removeClass().addClass(color);
createCookie("color",color);
return false;
});

if (readCookie("color") != null) {
$("body").removeClass().addClass(readCookie("color"));

}
else {
$("body").removeClass().addClass("red");
}
});

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ')
c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

Working example here. A thank you to QuirksMode for the pre-made cookie code (cookie-cutter cookie code?)

Using a cookie to remove and add classes to list items

Here is a working example -> http://jsfiddle.net/k6r86/ using cookies.js :

$(document).ready(function () {
var index = Cookies.get('active');
$('.clearfix').find('a').removeClass('active');
$(".clearfix").find('a').eq(index).addClass('active');
$('.clearfix').on('click', 'li a', function (e) {
e.preventDefault();
$('.clearfix').find('a').removeClass('active');
$(this).addClass('active');
Cookies.set('active', $('.clearfix a').index(this));
});
});

See the fiddle, click around and then update the fiddle again and see it had stored the active <li> and sets that <li>'s class to active on reload. I have disabled the links, not an error, simply for test.

how to save class name in cookies by using jquery?

You could use the jQuery cookie plugin: https://github.com/carhartl/jquery-cookie

The usage in your example is as follows:

jQuery(document).ready(function(){

//check if cookie has been set
var cookieColor = $.cookie("selected_class");
if (cookieColor) {
//remove default "red" class and add cookie class
$(".red").removeClass("red").addClass(cookieColor);
}

jQuery(document).on('click',".red-btn",function (){
alert("red color");
//store the value
$.cookie("selected_class", "red");

jQuery(".green").removeClass("green").addClass("red");
});
jQuery(document).on('click',".green-btn",function (){
alert("green color");

//store the value
$.cookie("selected_class", "green");
jQuery(".red").removeClass("red").addClass("green");
});
});

how to remove previous class and add new class in jquery?

Have you looked at removeClass

i.e

$("#hiddenTag").removeClass('someclass').addClass(elementID);

And if you don't know the class name:

$("#hiddenTag").removeAttr('class').addClass(elementID);

jQuery add class and remove all others

You could do it this way

http://jsfiddle.net/lollero/ZUJUB/

$(document).ready(function() {
$(".home, .services, .pricing, .special-thing, .contact").on("click", function() {

$(".primary-color")
// Remove all classes
.removeClass()
// Put back .primary-color class + the clicked elements class with the added prefix "pm_".
.addClass('primary-color pm_' + $(this).attr('class') );
});
});​

CSS:

.primary-color {
width: 100px;
height: 100px;
border: 1px solid #e1e1e1;

}

.pm_services { background: red; }
.pm_home { background: green; }

HTML:

<div class="services">services</div>
<div class="home">home</div>

<div class="primary-color">Primary-color</div>



or something like this:

http://jsfiddle.net/lollero/ZUJUB/1/

This fitted into the OP's structure: http://jsfiddle.net/lollero/EXq83/5/

jQuery:

$(document).ready(function() {
$("#buttons > div").on("click", function() {

$(".primary-color")
// Remove all classes
.removeClass()
// Put back .primary-color class + the clicked elements index with the added prefix "pm_".
.addClass('primary-color pm_' + ( $(this).index() + 1 ) );
});
});​

CSS:

.primary-color {
width: 100px;
height: 100px;
border: 1px solid #e1e1e1;

}

.pm_1 { background: red; }
.pm_2 { background: green; }

HTML:

<div id="buttons">
<div class="services">services</div>
<div class="home">home</div>
</div>

<div class="primary-color">Primary-color</div>

jQuery replace one class with another

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 ');

Add and remove a class on click using jQuery?

Why not try something like this?

$('#menu li a').on('click', function(){
$('#menu li a.current').removeClass('current');
$(this).addClass('current');
});

JSFiddle

Using JQuery removeClass() to remove all classes but one

You can pass a function to remove class, which returns all but the static Classes:

$('.staticClass').removeClass(function(index, klass) { 
return klass.replace(/(^|\s)+staticClass\s+/, '');
})

This is returning all the classes that are on the object, without the static one, and therefore removes all classes but the static one.

How can I remove all CSS classes using jQuery/JavaScript?

$("#item").removeClass();

Calling removeClass with no parameters will remove all of the item's classes.


You can also use (but it is not necessarily recommended. The correct way is the one above):

$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';

If you didn't have jQuery, then this would be pretty much your only option:

document.getElementById('item').className = '';


Related Topics



Leave a reply



Submit