Using JQuery removeClass() to remove all classes but one - javascript

Okay, I've got an interesting one (well, interesting to me, anyway :) ).
I've got a situation where I have a div with a static class value, but it also can have a single, "secondary class" assigned that is dynamic. When the user makes a selection, any existing secondary class needs to be removed and the new class added.
Ignoring using an id value (standards for the project use the class . . . can't be changed), is there an elegant way to simply ignore the first class and remove whatever other class is there, before adding the new one?
Example Starting HTML:
<div class="staticClass dynaClass1" />
Example JS:
function updateClass(newSecondaryClass) {
$(".staticClass") . . . **** remove any class besides "staticClass" ****
$(".staticClass").addClass(newSecondaryClass);
}
If the function is called using updateClass("dynaClass2");, the resulting HTML should be:
<div class="staticClass dynaClass2" />
I can think of ways of doing it involving just removing all classes using removeClass(); and adding "staticClass" back in when adding the new class, or using attr("class", "staticClass " + newSecondaryClass);, but I'm wondering if there isn't a way to handle it without having to touch the static class at all?
In the end, I guess this is an academic question, more than anything . . . just seems like it's something that should be doable, but I don't know how to do it. :D

You can remove all classes and add the one you want to leave:
$(".staticClass").removeClass().addClass('staticClass');
Calling removeClass() without a parameter removes all classes.
If you don't want to do that then you can simply modify the class attribute:
$(".staticClass").attr('class', 'staticClass');

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.

Pass a function to .removeClass()
A revision of Beat Richartz's answer on this page.
Note: I tried to post this as an edit and it was rejected. The concept is identical, with an improved RegEx.
Improved RegEx provides word-boundary matching with multiple classes
// Remove all classes except those specified
$('span').removeClass(function () {
return $(this).attr('class').replace(/\b(?:hello|world)\b\s*/g, '');
});
Before:
<span class="hello foo">hello</span> <span class="world bar">world</span>`
After:
<span class="hello">hello</span> <span class="world">world</span>`
Try it: http://jsfiddle.net/gfullam/52eeK/3/
Try it as a jQuery plugin: http://jsfiddle.net/gfullam/52eeK/5/
FWIW: This method is necessary when you don't want to replace the existing classes with other classes as in .attr('class', '<final list of classes>'), but instead just want to remove those that don't match a list of classes.

You can set it's required classes using the .attr() function. So:
$('.staticClass').attr('class','<any classes required');
This will replace any classes that were originally there, and add the new ones.

All of your classes are manipulated by calling the Javascript DOM element.className, so basically jQuery's addClass just replaces that string. You can see that in the Github source.
Which all means that if you call
$('.staticClass').addClass('someClass');
The element.className is replaced anyway, but with the new class included. ( this means that your staticClass is actually touched :)
When you call
$('.staticClass').removeClass().addClass('staticClass');
you will replace that string twice and there is no problem doing that.

Related

Removing classes defined by a jQuery attribute selector from the results of a jQuery attribute selector

Basic problem, I just want to target all classes that end with a specified string on all elements of a class that ends with a specified string, and remove those classes.
This code doesn't work, but it's close to what I want:
$('[class$="_active"]').removeClass($('[class$="_active"]'))
$('[class$="_active"]') returns a jQuery.fn.init object which I can work through with .each(index,item). I thought it would then be as simple as item.removeClass($('[class$="_active"]')) but the code below does not work either:
$('[class$="_active"]').each(function(index,item){
item.removeClass($('[class$="_active"]'))
})
The removeClass function does not work on the items in my each function. At this point I'm considering stringifying each item, figuring out the text immediately before "_active", removing it from the string along with "_active", then returning the reformed result. But this is just getting too complicated for a basic problem that I assume has a basic answer that I overlooked.
You can use attribute containing selector and attribute ends with selector to get all element with a certain class which ends with _active. To remove the class first you have to extract the certain class from the class list using String#match method(it's only necessary if there are multiple classes for an element).
$('[class$="_active"],[class*="_active "]').each(function(){
$(this).removeClass($(this).attr('class').match(/\S+_active\b/)[0])
// or $(this).removeClass(this.className.match(/\S+_active\b/)[0])
})
Just one lovely Solution
$('[class$="_active"]').each(function(i){$(this).removeClass(this.className)})
this is my jsfiddle link, have a look
https://jsfiddle.net/dupinderdhiman/mgzf2boL/7/

How to remove all instances of a class in javascript/jquery?

I have this class called .m-active that is used multiple times throughout my HTML.
Basically what I want to do is remove all instances of that class when a user clicks on an image (which does not have the m-active class) and add the m-active class to that image.
For instance in a Backgrid row you might have a click handler as follows:
"click": function () {
this.$el.addClass('m-active');
}
But you also want to remove that class from any rows to which it was previously added, so that only one row at a time has the .m-active class
Does anyone know how this can be done in javascript/jquery?
With jQuery:
$('.m-active').removeClass('m-active');
Explanation:
Calling $('.m-active') selects all elements from the document that contain class m-active
Whatever you chain after this selector gets applied to all selected elements
Chaining the call with removeClass('m-active') removes class m-active from all of the selected elements
For documentation on this specific method, see: http://api.jquery.com/removeClass/
Getting grasp of the whole selector thing with jQuery is challenging at first, but once you get it, you see everything in very different light. I encourage you to take a look into some good jQuery tutorials. I personally recommend checking out Codeacademy's jQuery track: http://www.codecademy.com/tracks/jquery
all answers point to remove the class from the DOM element. But if you are asking to remove the element itself you can user .remove() jquery method
$('.m-active').remove();
JQuery Remove Docs
In plain JavaScript (no jquery):
for (elem of document.getElementsByClassName("m-active")) {
elem.classList.remove("m-active");
}
Jquery-:
$("class").removeClass("your class");
javascript-:
Set the class name to nothing when you want to remove class in javascript!!!
document.getElementById("your id").className = "";
or
element.classList.remove("class name");
Specifically addressing the code block added to strengthen the quality of the question, and borrowing from jsalonen:
"click": function () {
$('.m-active').removeClass('m-active');
this.$el.addClass('m-active');
}

Find the child of the element represented by "this" that has a certain class

I know how to accomplish this if I can identify this element using a selector:
$("selector.class")
But what if my selector is the keyword this? Obviously $(this".class") isn't going to work, and I don't want to use $(this).children(".class") because then I need to extract the HTML of the element using .html(), and while I know that there will only be one element of this class in the selected element (I'm writing the HTML), JQuery doesn't, and it assumes that children() returns several elements when used with a class (at lease I think that's what it does, because
$(this).children(".class").html()
returns undefined).
Is there an other way I could do this?
Please feel free to ask for clarification, I understand this may not seem clear to some.
EDIT: some of you asked for clarification, so here it is. Let me rephrase the question: normally, when I ask JQuery to get me some elements, and give it a class as a selector it assumes I will get more than one element back and therefore $(".selector").html() doesn't work, because you can't get the HTML of several elements (at least that's my theory). Instead, I want it to recognise that in this case I am only getting 1 element back, and treat is as such. My restriction is that part of my selector is this. I hope that helped!
It isn't entirely clear to me what question you're asking so here are several different options:
To search for any subordinate tags (in the DOM tree with this as its root) that match a desired selector:
$(this).find(".myClass");
Or, if you're just trying to see if the this element has a particular class name, you can use:
if ($(this).hasClass("myClass")) {
// this element has the desired class
}
or, if the selector is more complicated than just a class, you can use .is() like this:
if ($(this).is("selector")) {
// this element matches desired selector
}
Really this isn't a selector, but I think you can do:
$(".class", this)
This is an example of supplying the context argument to the jQuery ($) function
For example (jsfiddle here),
HTML:
<div id="dis">hello
<div class="cls">
hi</div></div>
<div class="cls">
goodbye</div>
jQuery:
$(function () {
$('#dis').click(function () {
alert(
$('.cls', this).html());
});
});
will alert "hi" when the "dis" div is clicked.
Jquery is just a layer on top of JavaScript.
Just use raw javascript to get what you're looking for.
var childOfThis = this.querySelector('.myClass');

The right way to remove a class with jQuery

I have a simple question that interests me a lot:
If I want to remove a CSS class with jQuery, what's the right way?
1. removing after checking for the existence of the class?
if($(div).hasClass('css-class')) {
$(div).removeClass('css-class');
}
2. just removing it?
$(div).removeClass('css-class');
3.any other suggestions?
Just remove it. It's not like jQuery's going to throw an error (or anything like that) if the element does not have the class you're removing.
$(div).removeClass('css-class');
For removing class using jquery I prefer the 1st option for checking existence of class for a specific dom element and then remove the class applied for that DOM element eventhough jquery does not throw any error even if that DOM element has not been applied that class
E.g.
if($(div).hasClass('css-class')) {
$(div).removeClass('css-class');
}

Which is better practice for adding a class using jQuery?

$("#" + parentElementId + " label").attr("class", "disabled")
VS
$('#radiolabel').addClass('disabled');
Which are the pros and cons?
Thanks
The two are not the same. Using attr will replace the whole attribute. addClass will add the class to the existing classes.
As the name suggests addClass is made for this specific purpose, so I'd use that.
Here are some advantages of the two ways to do this:
addClass("disabled") Pros:
If you have other classes on your object, addClass() will preserve those while adding a new class. I pretty much always want to preserve the ability to use other classes for CSS styling reasons or common selector reasons so addClass() makes it possible to add the disabled class without disturbing other classes on the same object for other reasons.
The code reads a little more self-explanatory since the name addClass() tells someone reading the code exactly what it's doing.
addClass() automatically manages separators between class names so there is no extra accumulation of separators when you have multiple class names which can occur if you just get the current classname and add onto it yourself with string manipulation.
attr("class") = "disabled" Pros:
If you only ever want one class name on the object, this one statement insures that you will have only one class name.
A direct assignment of the one class can be faster than addClass() which has to examine what's there first and add a class to the pre-existing classes which jQuery does with a regex match. Max speed would actually be with element.className = "disabled" (no jQuery at all).
I'd go for addClass, it's easier to read, and if your editor supports code completion, also faster to type.
You better go for the addClass() you will save time and writting, and gain more efficiency.

Categories

Resources