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

Instead of individually calling $("#item").removeClass() for every single class an element might have, is there a single function which can be called which removes all CSS classes from the given element?
Both jQuery and raw JavaScript will work.

$("#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 = '';

Hang on, doesn't removeClass() default to removing all classes if nothing specific is specified? So
$("#item").removeClass();
will do it on its own...

Just set the className attribute of the real DOM element to '' (nothing).
$('#item')[0].className = ''; // the real DOM element is at [0]
Other people have said that just calling removeClass works - I tested this with the Google jQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:
$("#item").removeClass();

Of course.
$('#item')[0].className = '';
// or
document.getElementById('item').className = '';

Remove specific classes:
$('.class').removeClass('class');
Say if element has class="class another-class".

The shortest method
$('#item').removeAttr('class').attr('class', '');

You can just try:
$(document).ready(function() {
$('body').find('#item').removeClass();
});
If you have to access that element without a class name, for example you have to add a new class name, you can do this:
$(document).ready(function() {
$('body').find('#item').removeClass().addClass('class-name');
});
I use that function in my project to remove and add classes in an HTML builder.

I like using native JavaScript to do this, believe it or not!
solution 1: className
Remove all class of all items
const items = document.querySelectorAll('item');
for (let i = 0; i < items.length; i++) {
items[i].className = '';
}
Only remove all class of the first item
const item1 = document.querySelector('item');
item1.className = '';
solution 2: classList
// remove all class of all items
const items = [...document.querySelectorAll('.item')];
for (const item of items) {
item.classList.value = '';
}
// remove all class of the first item
const items = [...document.querySelectorAll('.item')];
for (const [i, item] of items.entries()) {
if(i === 0) {
item.classList.value = '';
}
}
// or
const item = document.querySelector('.item');
item.classList.value = '';
jQuery ways (not recommended)
$("#item").removeClass();
$("#item").removeClass("class1 ... classn");
refs
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

$('#elm').removeAttr('class');
Attribute "class" will no longer be present in "elm".

Since not all versions of jQuery are created equal, you may run into the same issue I did, which means calling $("#item").removeClass(); does not actually remove the class (probably a bug).
A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.
document.getElementById("item").removeAttribute("class");

Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.
This jQuery filter will remove the class "highlightCriteria" only for
the input or select fields that have this class.
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});

Try with removeClass.
For instance:
var nameClass=document.getElementsByClassName("clase1");
console.log("after", nameClass[0]);
$(".clase1").removeClass();
var nameClass=document.getElementsByClassName("clase1");
console.log("before", nameClass[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clase1">I am a Div with class="clase1"</div>

I had a similar issue. In my case, on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jQuery to remove this class on every element/control I want and everything works and looks great now.
This is my code for removing aspNetDisabled class:
$(document).ready(function () {
$("span").removeClass("aspNetDisabled");
$("select").removeClass("aspNetDisabled");
$("input").removeClass("aspNetDisabled");
});

Related

how to get one class from multiple classes in javascript

let check1 = document.querySelectorAll('.container input');
check1.forEach((elem)=>{
elem.addEventListener('click',()=>{
let boxes = document.querySelectorAll('.boxes');
boxes.forEach((ele)=>{
let boxesId = ele.getAttribute("class");
console.log(boxesId) //now there are three classes shown (boxes karat size)how to get size class
})
})
})
i am trying to get one class from multiple classes in javascript
Instead of using
ele.getAttribute("class");
Use the classList property.
let boxesId = ele.classList[2];
classList will return a list of all the classes. See documantation
Why you wanna do this? Sorry i can't understand.
But if you wann check if a element have a clas you can use the method includes.
element.classList.contains(className)

Select tags that starts with "x-" in jQuery

How can I select nodes that begin with a "x-" tag name, here is an hierarchy DOM tree example:
<div>
<x-tab>
<div></div>
<div>
<x-map></x-map>
</div>
</x-tab>
</div>
<x-footer></x-footer>
jQuery does not allow me to query $('x-*'), is there any way that I could achieve this?
The below is just working fine. Though I am not sure about performance as I am using regex.
$('body *').filter(function(){
return /^x-/i.test(this.nodeName);
}).each(function(){
console.log(this.nodeName);
});
Working fiddle
PS: In above sample, I am considering body tag as parent element.
UPDATE :
After checking Mohamed Meligy's post, It seems regex is faster than string manipulation in this condition. and It could become more faster (or same) if we use find. Something like this:
$('body').find('*').filter(function(){
return /^x-/i.test(this.nodeName);
}).each(function(){
console.log(this.nodeName);
});
jsperf test
UPDATE 2:
If you want to search in document then you can do the below which is fastest:
$(Array.prototype.slice.call(document.all)).filter(function () {
return /^x-/i.test(this.nodeName);
}).each(function(){
console.log(this.nodeName);
});
jsperf test
There is no native way to do this, it has worst performance, so, just do it yourself.
Example:
var results = $("div").find("*").filter(function(){
return /^x\-/i.test(this.nodeName);
});
Full example:
http://jsfiddle.net/6b8YY/3/
Notes: (Updated, see comments)
If you are wondering why I use this way for checking tag name, see:
JavaScript: case-insensitive search
and see comments as well.
Also, if you are wondering about the find method instead of adding to selector, since selectors are matched from right not from left, it may be better to separate the selector. I could also do this:
$("*", $("div")). Preferably though instead of just div add an ID or something to it so that parent match is quick.
In the comments you'll find a proof that it's not faster. This applies to very simple documents though I believe, where the cost of creating a jQuery object is higher than the cost of searching all DOM elements. In realistic page sizes though this will not be the case.
Update:
I also really like Teifi's answer. You can do it in one place and then reuse it everywhere. For example, let me mix my way with his:
// In some shared libraries location:
$.extend($.expr[':'], {
x : function(e) {
return /^x\-/i.test(this.nodeName);
}
});
// Then you can use it like:
$(function(){
// One way
var results = $("div").find(":x");
// But even nicer, you can mix with other selectors
// Say you want to get <a> tags directly inside x-* tags inside <section>
var anchors = $("section :x > a");
// Another example to show the power, say using a class name with it:
var highlightedResults = $(":x.highlight");
// Note I made the CSS class right most to be matched first for speed
});
It's the same performance hit, but more convenient API.
It might not be efficient, but consider it as a last option if you do not get any answer.
Try adding a custom attribute to these tags. What i mean is when you add a tag for eg. <x-tag>, add a custom attribute with it and assign it the same value as the tag, so the html looks like <x-tag CustAttr="x-tag">.
Now to get tags starting with x-, you can use the following jQuery code:
$("[CustAttr^=x-]")
and you will get all the tags that start with x-
custom jquery selector
jQuery(function($) {
$.extend($.expr[':'], {
X : function(e) {
return /^x-/i.test(e.tagName);
}
});
});
than, use $(":X") or $("*:X") to select your nodes.
Although this does not answer the question directly it could provide a solution, by "defining" the tags in the selector you can get all of that type?
$('x-tab, x-map, x-footer')
Workaround: if you want this thing more than once, it might be a lot more efficient to add a class based on the tag - which you only do once at the beginning, and then you filter for the tag the trivial way.
What I mean is,
function addTagMarks() {
// call when the document is ready, or when you have new tags
var prefix = "tag--"; // choose a prefix that avoids collision
var newbies = $("*").not("[class^='"+prefix+"']"); // skip what's done already
newbies.each(function() {
var tagName = $(this).prop("tagName").toLowerCase();
$(this).addClass(prefix + tagName);
});
}
After this, you can do a $("[class^='tag--x-']") or the same thing with querySelectorAll and it will be reasonably fast.
See if this works!
function getXNodes() {
var regex = /x-/, i = 0, totalnodes = [];
while (i !== document.all.length) {
if (regex.test(document.all[i].nodeName)) {
totalnodes.push(document.all[i]);
}
i++;
}
return totalnodes;
}
Demo Fiddle
var i=0;
for(i=0; i< document.all.length; i++){
if(document.all[i].nodeName.toLowerCase().indexOf('x-') !== -1){
$(document.all[i].nodeName.toLowerCase()).addClass('test');
}
}
Try this
var test = $('[x-]');
if(test)
alert('eureka!');
Basically jQuery selector works like CSS selector.
Read jQuery selector API here.

remove everything that is inside the actual tag [duplicate]

Is it possible to remove all attributes at once using jQuery?
<img src="example.jpg" width="100" height="100">
to
<img>
I tried $('img').removeAttr('*'); with no luck. Anyone?
A simple method that doesn't require JQuery:
while(elem.attributes.length > 0)
elem.removeAttribute(elem.attributes[0].name);
Update: the previous method works in IE8 but not in IE8 compatibility mode and previous versions of IE. So here is a version that does and uses jQuery to remove the attributes as it does a better job of it:
$("img").each(function() {
// first copy the attributes to remove
// if we don't do this it causes problems
// iterating over the array we're removing
// elements from
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// now use jQuery to remove the attributes
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
Of course you could make a plug-in out of it:
jQuery.fn.removeAttributes = function() {
return this.each(function() {
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
}
and then do:
$("img").removeAttributes();
One-liner, no jQuery needed:
[...elem.attributes].forEach(attr => elem.removeAttribute(attr.name));
Instead of creating a new jQuery.fn.removeAttributes (demonstrated in the accepted answer) you can extend jQuery's existing .removeAttr() method making it accept zero parameters to remove all attributes from each element in a set:
var removeAttr = jQuery.fn.removeAttr;
jQuery.fn.removeAttr = function() {
if (!arguments.length) {
this.each(function() {
// Looping attributes array in reverse direction
// to avoid skipping items due to the changing length
// when removing them on every iteration.
for (var i = this.attributes.length -1; i >= 0 ; i--) {
jQuery(this).removeAttr(this.attributes[i].name);
}
});
return this;
}
return removeAttr.apply(this, arguments);
};
Now you can call .removeAttr() without parameters to remove all attributes from the element:
$('img').removeAttr();
One very good reason to do this for specific tags is to clean up legacy content and also enforce standards.
Let's say, for example, you wanted to remove legacy attributes, or limit damage caused by FONT tag attributes by stripping them.
I've tried several methods to achieve this and none, including the example above, work as desired.
Example 1: Replace all FONT tags with the contained textual content.
This would be the perfect solution but as of v1.6.2 has ceased to function. :(
$('#content font').each(function(i) {
$(this).replaceWith($(this).text());
});
Example 2: Strip all attributes from a named tag - e.g. FONT.
Again, this fails to function but am sure it used to work once upon a previous jQuery version.
$("font").each(function() {
// First copy the attributes to remove.
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// Now remove the attributes
var font = $(this);
$.each(attributes, function(i, item) {
$("font").removeAttr(item);
});
});
Looking forward to 1.7 which promises to include a method to remove multiple attributes by name.
One-liner.
For jQuery users
$('img').removeAttr(Object.values($('img').get(0).attributes).map(attr => attr.name).join(' '));
One don't need to refer to the name of attribute to to id nowadays, since we have
removeAttributeNode method.
while(elem.attributes.length > 0) {
elem.removeAttributeNode(elem.attributes[0]);
}
I don't know exactly what you're using it for, but have you considered using css classes instead and toggling those ? It'll be less coding on your side and less work for the browser to do. This will probably not work [easily] if you're generating some of the attributes on the fly like with and height.
This will remove all attributes and it will work for every type of element.
var x = document.createElement($("#some_id").prop("tagName"));
$(x).insertAfter($("#some_id"));
$("#some_id").remove();
Today I have same issue. I think that it will be useful for you
var clone = $(node).html();
clone = $('<tr>'+ clone +'</tr>');
clone.addClass('tmcRow');

How can I replace a class with another using jQuery?

What jquery can I use to change the class that's used in the following from indent_1 to indent_2 or indent_4 to indent_2? I know about remove class but how can I do that when the classes are names that vary?
<div class="rep_td0 indent_1" id="title_1">Menu two</div>
or
<div class="rep_td0 indent_4" id="title_1">Menu two</div>
Since you haven't been very specific about exactly what class you want to change to another and you've said you want to deal with the case where you don't know exactly what the class is, here are some ideas:
You can find all objects that have a class that starts with "indent_" with this selector:
$('[className^="indent_"]')
If you wanted to examine the class on each one of those objects, you could iterate over that jQuery object with .each() and decide what to do with each object or you could use removeClass() with a custom function and examine the class name and decide what to do with it.
If you just wanted to change all indent class names to indent_2, then you could use this:
$('[className^="indent_"]').removeClass("indent_1 indent_3 indent_4").addClass("indent_2");
or, using a custom function that can examine the class name with a regex:
$('[className^="indent_"]').removeClass(function(index, name) {
var match = name.match(/\bindent_\d+\b/);
if (match) {
return(match[0]);
} else {
return("");
}
}).addClass("indent_2");
Or, if all you want to do is find the object with id="title_1" and fix it's classname, you can do so like this:
var o = document.getElementById("title_1");
o.className = o.className.replace(/\bindent_\d+\b/, "indent_2");
You can see this last one work here: http://jsfiddle.net/jfriend00/tF8Lw/
If you're trying to make this into a function that could take different numbers, you could use this:
function changeIndentClass(id, indentNum) {
var item = document.getElementById(id);
item.className = item.className(/\bindent_\d+\b/, "indent_" + indentNum);
}
try this code,
$("#title_1").removeClass("indent_1").addClass("indent_2");
if you not sure which is available, try this
$("#title_1").removeClass("indent_1").removeClass("indent_4").addClass("indent_2");
Updated:
$("#title_1").removeClass(function() {
var match = $(this).attr('class').match(/\bindent_\d+\b/);
if (match) {
return (match[0]);
} else {
return ("");
}
}).addClass("indent_2");
Try below :
$('#title_1').removeClass('indent_1').addClass('indent_2');
Here, the indent_1 classes will be replaced with indent_2.
Maybe this?: Remove all classes that begin with a certain string
That answers how to replace a classname on a jQuery element that has a specific prefix, such as 'indent_'.
While that answer doesn't specifically address replacement, you can achieve that by altering one of their answers slightly:
$("selector").className = $("selector").className.replace(/\bindent.*?\b/g, 'indent_2');
Or similar...
First things first...If you have multiple elements on your page with the exact same ID you're going to have problems selecting them by ID. Some browsers won't work at all while others may return just the first element that matches.
So you'll have to clean up the ID thing first.
You can use the starts with selector to find all the classes that match your class name patter and then decide if you want to switch them or not:
$('[class^="indent_"]').each(function() {
var me = $(this);
if(me.hasClass("indent_1").removeClass("indent_1").addClass("indent_2");
});

How to dynamically remove a stylesheet from the current page

Is there a way to dynamically remove the current stylesheet from the page?
For example, if a page contains:
<link rel="stylesheet" type="text/css" href="http://..." />
...is there a way to later disable it with JavaScript? Extra points for using jQuery.
Well, assuming you can target it with jQuery it should be just as simple as calling remove() on the element:
$('link[rel=stylesheet]').remove();
That will remove all external stylesheets on the page. If you know part of the url then you can remove just the one you're looking for:
$('link[rel=stylesheet][href~="foo.com"]').remove();
And in Javascript
this is an example of remove all with query selector and foreach array
Array.prototype.forEach.call(document.querySelectorAll('link[rel=stylesheet]'), function(element){
try{
element.parentNode.removeChild(element);
}catch(err){}
});
//or this is similar
var elements = document.querySelectorAll('link[rel=stylesheet]');
for(var i=0;i<elements.length;i++){
elements[i].parentNode.removeChild(elements[i]);
}
If you know the ID of the stylesheet, use the following. Any other method of getting the stylesheet works as well, of course. This is straight DOM and doesn't require using any libraries.
var sheet = document.getElementById(styleSheetId);
sheet.disabled = true;
sheet.parentNode.removeChild(sheet);
I found this page whilst looking for a way to remove style sheets using jquery. I thought I'd found the right answer when I read the following
If you know part of the url then you can remove just the one you're looking for:
$('link[rel=stylesheet][href~="foo.com"]').remove();"
I liked this solution because the style sheets I wanted to remove had the same name but were in different folders. However this code did not work so I changed the operator to *= and it works perfectly:
$('link[rel=stylesheet][href*="mystyle"]').remove();
Just thought I'd share this in case it's useful for someone.
This will disable any stylesheet matching the regular expression searchRegEx provided against the URL of each stylesheet.
let searchRegEx = /example.*/;
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href.search(searchRegEx) != -1) {
document.styleSheets[i].disabled = true;
}
}
Nobody has mentioned removing a specific stylesheet without an ID in plain Javascript:
document.querySelector('link[href$="something.css"]').remove()
("$=" to find at end of href)
This will reset your page's styling, removing all of the style-elements. Also, jQuery isn't required.
Array.prototype.forEach.call(document.querySelectorAll('style,[rel="stylesheet"],[type="text/css"]'), function(element){
try{
element.parentNode.removeChild(element)
}catch(err){}
});
This is for disable all <style> from html
// this disable all style of the website...
var cant = document.styleSheets.length
for(var i=0;i<cant;i++){
document.styleSheets[i].disabled=true;
}
//this is the same disable all stylesheets
Array.prototype.forEach.call(document.styleSheets, function(element){
try{
element.disabled = true;
}catch(err){}
});
To expand on Damien's answer, the test method (which returns true or false) would probably be a better fit than search and is slightly faster. Using this method would yield:
for (var i = 0; i < document.styleSheets.length; i++) {
if (/searchRegex/.test(document.styleSheets[i].href)) {
document.styleSheets[i].disabled = true;
}
}
If you don't care about IE support this can be cleaned up with a for...of loop
for (const styleSheet of document.styleSheets) {
if (/searchRegex/.test(styleSheet)) {
styleSheet.disabled = true;
}
}
Suppose you want to remove a class myCssClass then the most easy way to do it is element.classList.remove("myCssClass");

Categories