How to select and remove class from an element based on string?
E.g
How to remove class="s2"
from element <p class="s2 s4 s5"></p>
I'm looking for way to select class based on number - e.g 's' can be string on any signs. Please note that the order can be different.
Any suggestion much appreciated.
This post will discuss how to remove a specific CSS class from an HTML element using JavaScript and jQuery... With jQuery, you can use the .removeClass() method for removing the specific class from an element. TECHIE DELIGHT </>
Consider we have a div element that is styled using the container class. At some point we need to remove all styles added to the div element, we can do that by adding all css property with value initial. The initial css keyword restores the element styles to the initial state or default state which is set by the browser.
We can also remove styles easily by removing the class name added to that element using JavaScript.
In plain JavaScript, you can use the removeAttribute () method to remove the class attribute from an element. To remove all the inline styles as well, you can remove the style attribute as well. 5. Using JavaScript’s className property
What you're looking for is .removeClass:
$('p.s4.s5').removeClass('s2');
$('p').removeClass(function(i, class) {
var classes = class.split(' '); //get an array of all the classes
var remove = []; //classes to remove
$.each(classes, function() {
if(this.match(/2$/)) //if the class name ends in 2
remove.push(this); //add it to the list of classes to remove
});
return remove.join(' ');
});
demo
Try this:
//Get an array of css classes
var aryClasses = $('p').attr('class').split(' ');
//Loop over array and check if 2 exists anywhere in the class name
for(var i = 0; i < aryClasses.length; i++)
{
//Check if 2 exists in the class name
if(aryClasses[i].indexOf('2') != -1)
{
//2 Exists, remove the class
$('.s2').removeClass(aryClasses[i]);
}
}
Here's a working JS Fiddle
EDIT
As someone pointed out in the comments, the above code will only remove the CSS classes from the first p
tag (as per your example). The code below will remove all CSS classes ending in two from all p
elements.
$('p').each(function() {
var aryClasses = $(this).attr('class').split(' ');
for (var i = 0; i < aryClasses.length; i++) {
if (aryClasses[i].indexOf('2') != -1) {
$(this).removeClass(aryClasses[i]);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With