How to add/remove a class in JavaScript? - javascript

Since element.classList is not supported in IE 9 and Safari-5, what's an alternative cross-browser solution?
No-frameworks please.
Solution must work in at least IE 9, Safari 5, FireFox 4, Opera 11.5, and Chrome.
Related posts (but does not contain solution):
how to add and remove css class
Add and remove a class with animation
Add remove class?

Here is solution for addClass, removeClass, hasClass in pure javascript solution.
Actually it's from http://jaketrent.com/post/addremove-classes-raw-javascript/
function hasClass(ele,cls) {
return !!ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}

Look at these oneliners:
Remove class:
element.classList.remove('hidden');
Add class (will not add it twice if already present):
element.classList.add('hidden');
Toggle class (adds the class if it's not already present and removes it if it is)
element.classList.toggle('hidden');
That's all! I made a test - 10000 iterations. 0.8s.

I just wrote these up:
function addClass(el, classNameToAdd){
el.className += ' ' + classNameToAdd;
}
function removeClass(el, classNameToRemove){
var elClass = ' ' + el.className + ' ';
while(elClass.indexOf(' ' + classNameToRemove + ' ') !== -1){
elClass = elClass.replace(' ' + classNameToRemove + ' ', '');
}
el.className = elClass;
}
I think they'll work in all browsers.

The simplest is element.classList which has remove(name), add(name), toggle(name), and contains(name) methods and is now supported by all major browsers.
For older browsers you change element.className. Here are two helper:
function addClass(element, className){
element.className += ' ' + className;
}
function removeClass(element, className) {
element.className = element.className.replace(
new RegExp('( |^)' + className + '( |$)', 'g'), ' ').trim();
}

One way to play around with classes without frameworks/libraries would be using the property Element.className, which "gets and sets the value of the class attribute of the specified element." (from the MDN documentation).
As #matías-fidemraizer already mentioned in his answer, once you get the string of classes for your element you can use any methods associated with strings to modify it.
Here's an example:
Assuming you have a div with the ID "myDiv" and that you want to add to it the class "main__section" when the user clicks on it,
window.onload = init;
function init() {
document.getElementById("myDiv").onclick = addMyClass;
}
function addMyClass() {
var classString = this.className; // returns the string of all the classes for myDiv
var newClass = classString.concat(" main__section"); // Adds the class "main__section" to the string (notice the leading space)
this.className = newClass; // sets className to the new string
}

Read this Mozilla Developer Network article:
https://developer.mozilla.org/en/DOM/element.className
Since element.className property is of type string, you can use regular String object functions found in any JavaScript implementation:
If you want to add a class, first use String.indexOf in order to check if class is present in className. If it's not present, just concatenate a blank character and the new class name to this property. If it's present, do nothing.
If you want to remove a class, just use String.replace, replacing "[className]" with an empty string. Finally use String.trim to remove blank characters at the start and end of element.className.

Fixed the solution from #Paulpro
Do not use "class", as it is a reserved word
removeClass function
was broken, as it bugged out after repeated use.
`
function addClass(el, newClassName){
el.className += ' ' + newClassName;
}
function removeClass(el, removeClassName){
var elClass = el.className;
while(elClass.indexOf(removeClassName) != -1) {
elClass = elClass.replace(removeClassName, '');
elClass = elClass.trim();
}
el.className = elClass;
}

The solution is to
Shim .classList:
Either use the DOM-shim or use Eli Grey's shim below
Disclaimer: I believe the support is FF3.6+, Opera10+, FF5, Chrome, IE8+
/*
* classList.js: Cross-browser full element.classList implementation.
* 2011-06-15
*
* By Eli Grey, http://eligrey.com
* Public Domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
/*global self, document, DOMException */
/*! #source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/
if (typeof document !== "undefined" && !("classList" in document.createElement("a"))) {
(function (view) {
"use strict";
var
classListProp = "classList"
, protoProp = "prototype"
, elemCtrProto = (view.HTMLElement || view.Element)[protoProp]
, objCtr = Object
, strTrim = String[protoProp].trim || function () {
return this.replace(/^\s+|\s+$/g, "");
}
, arrIndexOf = Array[protoProp].indexOf || function (item) {
var
i = 0
, len = this.length
;
for (; i < len; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
}
// Vendors: please allow content code to instantiate DOMExceptions
, DOMEx = function (type, message) {
this.name = type;
this.code = DOMException[type];
this.message = message;
}
, checkTokenAndGetIndex = function (classList, token) {
if (token === "") {
throw new DOMEx(
"SYNTAX_ERR"
, "An invalid or illegal string was specified"
);
}
if (/\s/.test(token)) {
throw new DOMEx(
"INVALID_CHARACTER_ERR"
, "String contains an invalid character"
);
}
return arrIndexOf.call(classList, token);
}
, ClassList = function (elem) {
var
trimmedClasses = strTrim.call(elem.className)
, classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
, i = 0
, len = classes.length
;
for (; i < len; i++) {
this.push(classes[i]);
}
this._updateClassName = function () {
elem.className = this.toString();
};
}
, classListProto = ClassList[protoProp] = []
, classListGetter = function () {
return new ClassList(this);
}
;
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error's toString() is sufficient here.
DOMEx[protoProp] = Error[protoProp];
classListProto.item = function (i) {
return this[i] || null;
};
classListProto.contains = function (token) {
token += "";
return checkTokenAndGetIndex(this, token) !== -1;
};
classListProto.add = function (token) {
token += "";
if (checkTokenAndGetIndex(this, token) === -1) {
this.push(token);
this._updateClassName();
}
};
classListProto.remove = function (token) {
token += "";
var index = checkTokenAndGetIndex(this, token);
if (index !== -1) {
this.splice(index, 1);
this._updateClassName();
}
};
classListProto.toggle = function (token) {
token += "";
if (checkTokenAndGetIndex(this, token) === -1) {
this.add(token);
} else {
this.remove(token);
}
};
classListProto.toString = function () {
return this.join(" ");
};
if (objCtr.defineProperty) {
var classListPropDesc = {
get: classListGetter
, enumerable: true
, configurable: true
};
try {
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
} catch (ex) { // IE 8 doesn't support enumerable:true
if (ex.number === -0x7FF5EC54) {
classListPropDesc.enumerable = false;
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
}
}
} else if (objCtr[protoProp].__defineGetter__) {
elemCtrProto.__defineGetter__(classListProp, classListGetter);
}
}(self));
}

Improved version of emil's code (with trim())
function hasClass(ele,cls) {
return !!ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className = ele.className.trim() + " " + cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className = ele.className.replace(reg,' ');
ele.className = ele.className.trim();
}
}

function addClass(element, classString) {
element.className = element
.className
.split(' ')
.filter(function (name) { return name !== classString; })
.concat(classString)
.join(' ');
}
function removeClass(element, classString) {
element.className = element
.className
.split(' ')
.filter(function (name) { return name !== classString; })
.join(' ');
}

Just in case if anyone would like to have prototype functions built for elements, this is what I use when I need to manipulate classes of different objects:
Element.prototype.addClass = function (classToAdd) {
var classes = this.className.split(' ')
if (classes.indexOf(classToAdd) === -1) classes.push(classToAdd)
this.className = classes.join(' ')
}
Element.prototype.removeClass = function (classToRemove) {
var classes = this.className.split(' ')
var idx =classes.indexOf(classToRemove)
if (idx !== -1) classes.splice(idx,1)
this.className = classes.join(' ')
}
Use them like:
document.body.addClass('whatever') or document.body.removeClass('whatever')
Instead of body you can also use any other element (div, span, you name it)

add css classes: cssClassesStr += cssClassName;
remove css classes: cssClassStr = cssClassStr.replace(cssClassName,"");
add attribute 'Classes': object.setAttribute("class", ""); //pure addition of this attribute
remove attribute: object.removeAttribute("class");

A easy to understand way:
// Add class
DOMElement.className += " one";
// Example:
// var el = document.body;
// el.className += " two"
// Remove class
function removeDOMClass(element, className) {
var oldClasses = element.className,
oldClassesArray = oldClasses.split(" "),
newClassesArray = [],
newClasses;
// Sort
var currentClassChecked,
i;
for ( i = 0; i < oldClassesArray.length; i++ ) {
// Specified class will not be added in the new array
currentClassChecked = oldClassesArray[i];
if( currentClassChecked !== className ) {
newClassesArray.push(currentClassChecked);
}
}
// Order
newClasses = newClassesArray.join(" ");
// Apply
element.className = newClasses;
return element;
}
// Example:
// var el = document.body;
// removeDOMClass(el, "two")
https://gist.github.com/sorcamarian/ff8db48c4dbf4f5000982072611955a2

Related

JS: Replace a link with another word. Nested quotes + escape codes

Begin with a fresh plain HTML document, and only use HTML and Javascript.
Place on it the hyperlinked word ''food''
Upon clicking ''food'', it should be replaced with ''meat and vegetables''
Upon clicking ''meat'', it should be replaced with ''pork with bacon''
Upon clicking ''vegetables'', it should be replaced with ''carrots plus peas''
Upon clicking ''pork'', it should be replaced with ''tough and chewy''
Upon clicking ''tough'', it should be replaced with ''burnt and salty''
(And so on)
I've been trying to do this as far as I can, but I'm having escapecode problems.
Here is my code:
<span id="food">food</span>
Here it is in action: http://jsfiddle.net/jshflynn/L6r5rrfx/
I'm sorry it's not spaced, but that threw up errors.
Notice that ''alert(2)'' has no delimiting characters around it, I don't know how to make it say alert(''Hello'').
I feel there must be some recursive way to do this, but I'm not sure.
Thanks in advance. Especially so if you can do the full problem.
Here you go, you get the idea: http://jsfiddle.net/8bhd8njh/
function bind(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, !1);
return !0;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return !0;
}
}
String.prototype.supplant = function (a, b) {
return this.replace(/{([^{}]*)}/g, function (c, d) {
return void 0!=a[d]?a[d]:b?'':c
})
};
var data = {
food : '{meat} and {vegetables}',
meat : '{pork} and {beef}',
pork : '{tough} and {chewy}',
tough : '{burnt} and {salty}',
vegetables : '{carrots} and {peas}'
};
var classname = 'game-clickable';
var init = function(obj, data) {
var template = '<span class="{classname}">{text}</span>';
obj.innerHTML = obj.innerHTML.replace(/{([^{}]*)}/g, function(a,b) {
return template.supplant({
classname : data[b] ? classname : '',
text : b
}, !0)
});
var objects = document.getElementsByClassName('game-clickable');
for (var i = 0; i < objects.length; i++) {
bind(objects[i], 'click', (function(o) {
return function() {
if (!data[o.innerHTML]) {
return;
}
var parent = o.parentNode;
var span = document.createElement('SPAN');
span.innerHTML = data[o.innerHTML];
parent.insertBefore(span, o);
parent.removeChild(o);
init(parent, data);
}
})(objects[i]));
}
};
init(document.getElementById('word-game'), data);
.game-clickable {
cursor: pointer;
text-decoration: underline;
}
<div id="word-game">
{food}
</div>
I think you are looking for something like the following:
var replacements = {
"food" : "meat and vegetables",
"meat" : "pork with bacon",
"vegetables" : "carrots plus peas",
"pork" : "tough and chewy",
"tough" : "burnt and salty"
};
function replaceAnchor(a) {
var elementType = "";
var lastElementType = "";
var target = a.innerHTML;
var replacement = replacements[target];
var words = replacement.split(' ');
var newElement = {};
for(var i = 0; i < words.length; i++) {
var word = words[i];
if (replacements[word]) {
elementType = "a";
} else {
elementType = "span";
}
if (elementType === "a" || elementType != lastElementType) {
newElement = document.createElement(elementType);
if (elementType === "a") {
newElement.onclick = function(e) {
replaceAnchor(this);
e.preventDefault();
};
}
a.parentNode.insertBefore(newElement, a);
}
if (elementType == "span") {
newElement.innerHTML = newElement.innerHTML + " " + word + " ";
} else {
newElement.innerHTML += word;
}
lastElementType = elementType;
}
a.parentElement.removeChild(a);
return false;
}
a {
text-decoration : underline;
color : blue;
cursor: pointer;
}
<a onclick="return replaceAnchor(this);">food</a>

.replace on array element not working in a loop javascript

I wanted to write a function that gets all the dom elements with the class active and remove that class. I am trying to use the replace method by looping through the array obtained from getElementsByClassName('active') and using replace to replace it with a blank space. Two questions: why isn't the replace method removing the active class and what would be a better alternative to remove class with vanilla js.
function removeItem(){
var activeItems = document.getElementsByClassName('active');
for (i=0; i<activeItems.length; i++){
var activeClass = activeItems[i].className;
activeClass.replace('active', '')
}
}
.replace() returns a string, which you must store, it doesn't overwrite the variable.
activeClass = activeClass.replace('active',''); // this will still need to be set as the classname
Something like this:
function removeClass(){
var activeItems = document.getElementsByClassName('active');
for (var i=0,n=activeItems.length; i<n; i++){
var classes = activeItems[i].className.split(' ') || [];
for (var j=0,l=classes.length; j<l; j++){
if(classes[j] === 'active') {
classes.splice(j,1);
j--;l--; // we popped a value off the stack
}
}
activeItems[i].className = classes.join(' ');
}
}
or as zzzzBov suggests, go native:
activeItems[i].classList.remove('active');
Strings are passed by value in Javascript. You must set the changed string. Also, .replace doesn't change the string but returns a new one.
activeItems[i].className = activeItems[i].className.replace('active', '');
You can use the following set of functions to add and remove class names. Plain js, no library.
// Return true or false if el has className or not
function hasClassName (el, cName) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
return el && re.test(el.className);
}
// Add class to element if it doesn't have it already
function addClassName (el, cName) {
if (!hasClassName(el, cName)) {
el.className = trim(el.className + ' ' + cName);
}
}
// Remove className from element if it has it
function removeClassName(el, cName) {
if (hasClassName(el, cName)) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
el.className = trim(el.className.replace(re, ''));
}
}
// Remove leading and trailing whitespace, reduce remaining whitespace to
// a single character
function trim(s) {
return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}
To keep zzzzBov happy, here are the same function using a space instead of \s (also removed reliance on the RegExp constructor so should be faster too). I'd recommend sticking with \s as I haven't seen any convincing argument not to, but make you're own choice.
// Return true or false if el has className or not
function hasClassName (el, cName) {
return (' ' + el.className + ' ').indexOf(' ' + cName + ' ') != -1;
}
// Add class to element if it doesn't have it already
function addClassName (el, cName) {
if (!hasClassName(el, cName)) {
el.className = trimSpaces(el.className + ' ' + cName);
}
}
// Remove className from element if it has it
function removeClassName(el, cName) {
if (hasClassName(el, cName)) {
el.className = trimSpaces((' ' + el.className + ' ').replace(' ' + cName + ' ', ' '));
}
}
// Remove leading and trailing whitespace, reduce remaining whitespace to
// a single character
function trimSpaces(s) {
return s.replace(/(^ +)|( +$)/g,'').replace(/ +/g,' ');
}
You forgot to assign the className again.
activeItems[i].className = activeClass.replace(/(?:\s*)(active\s*)/, '');
Note that getElementsByClassName() might not work in older Browsers.
Raw JavaScript idea:
var doc = document;
function getClass(class){
if(doc.getElementsByClassName){
return doc.getElementsByClassName(class);
}
else{
var tags = doc.getElementsByTagName('*'), l = tags.length, r = [];
if(l < 1){
return false;
}
else{
var x = new RegExp('(^|\\s+)'+class+'(\\s+|$)');
for(var i=0; i<l; i++){
var tag = tags[i];
if(tag.className.match(x)){
r.push(tag);
}
}
return r;
}
}
}
function removeClass(class){
var cls = getClass(class), x = new RegExp('(^|\\s+)'+class+'(\\s+|$)');
for(var i=0,l=cls.length; i<l; i++){
var c = cls[i];
c.className = c.className.replace(x, '');
}
}

Custom Search DOM Elements

I am writing a custom method to return the DOM element reference but it seems to work on all modern browsers such as Chrome,Firefox,Safari but fails in IE 9 ... returned element is undefined it states i am not sure what i am doing wrong
var searchEle = function (parent, ref) {
var refEle;
if (typeof document.getElementByClassName === "function") {
if (ref.substr(0, 1) === ".") {
refEle = parent.getElementsByClassName(ref.replace(".", ""));
} else {
refEle = parent.getElementsByTagName(ref);
}
} else {
if (ref.substr(0, 1) === "#") {
refEle = parent.getElementById(ref.replace("#", ""));
} else if (ref.substr(0, 1) === ".") {
refEle = parent.querySelector(ref);
}
}
return refEle;
};
Check out demo here on IE9: http://jsbin.com/ubokop/5/edit
Thanks
First of all, use this polyfill for getElementsByClassName, since that's really the only function that requires one. It's not perfect, but it's close enough.
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', #class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while (i = elements.iterateNext()) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
(Source of this polyfill)
Then, this would be enough:
var searchEle = function (ref) {
if (ref.charAt(0) === "#") {
return document.getElementById(ref.substr(1));
}else if (ref.charAt(0) === ".") {
return document.getElementsByClassName(ref.substr(1));
}else{
return document.getElementsByTagName(ref);
}
};

Javascript Hide/Show Classes Issue

I have the following function that is supposed to get all elements in a document with the given class:
function getElementByClass(objClass)
{
// This function is similar to 'getElementByID' since there is no inherent function to get an element by it's class
var elements = (ie) ? document.all : document.getElementsByTagName('*');
for (i=0; i<elements.length; i++)
{
alert(elements[i].className);
alert(objClass);
if (elements[i].className==objClass)
{
return elements[i]
}
}
}
When I call this function with:
<script type="text/javascript">document.write(getElementByClass('done'));</script>
Nothing happens. Is there something wrong with the function?
This function does not get all elements with that class name, it gets one. And what is your intent with the way you are calling it? document.write seems like a funny thing to do with a DOM element already on your page.
I hate to just say "use jquery"... but you probably should.
Aside from the missing declaration of ie, this function does work. One problem you will have with it is if you have multiple classes on an element, this function won't work.
document.getElementsByClassName('done');
EDIT:
src: http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/
/*
Developed by Robert Nyman, http://www.robertnyman.com
Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
if (document.getElementsByClassName) {
getElementsByClassName = function (className, tag, elm) {
elm = elm || document;
var elements = elm.getElementsByClassName(className),
nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
returnElements = [],
current;
for(var i=0, il=elements.length; i<il; i+=1){
current = elements[i];
if(!nodeName || nodeName.test(current.nodeName)) {
returnElements.push(current);
}
}
return returnElements;
};
}
else if (document.evaluate) {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = "",
xhtmlNamespace = "http://www.w3.org/1999/xhtml",
namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
returnElements = [],
elements,
node;
for(var j=0, jl=classes.length; j<jl; j+=1){
classesToCheck += "[contains(concat(' ', #class, ' '), ' " + classes[j] + " ')]";
}
try {
elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
}
catch (e) {
elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
}
while ((node = elements.iterateNext())) {
returnElements.push(node);
}
return returnElements;
};
}
else {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = [],
elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
current,
returnElements = [],
match;
for(var k=0, kl=classes.length; k<kl; k+=1){
classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
}
for(var l=0, ll=elements.length; l<ll; l+=1){
current = elements[l];
match = false;
for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
match = classesToCheck[m].test(current.className);
if (!match) {
break;
}
}
if (match) {
returnElements.push(current);
}
}
return returnElements;
};
}
return getElementsByClassName(className, tag, elm);
};
if you have posted full source then what is ie in
var elements = (ie) ? document.all : document.getElementsByTagName('*');
try to track error via firebug.
var elements = (ie) is referencing an undefined variable ie
Have you considered using a JavaScript library? Functions like this have been written many times before, painful to waste time on these kinds of things.
You should probably use getElementsByClassName when available.

Remove CSS class from element with JavaScript (no jQuery) [duplicate]

This question already has answers here:
How can I change an element's class with JavaScript?
(33 answers)
Closed 8 years ago.
Could anyone let me know how to remove a class on an element using JavaScript only?
Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.
The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:
ELEMENT.classList.remove("CLASS_NAME");
remove.onclick = () => {
const el = document.querySelector('#el');
el.classList.remove("red");
}
.red {
background: red
}
<div id='el' class="red"> Test</div>
<button id='remove'>Remove Class</button>
Documentation: https://developer.mozilla.org/en/DOM/element.classList
document.getElementById("MyID").className =
document.getElementById("MyID").className.replace(/\bMyClass\b/,'');
where MyID is the ID of the element and MyClass is the name of the class you wish to remove.
UPDATE:
To support class names containing dash character, such as "My-Class", use
document.getElementById("MyID").className =
document.getElementById("MyID").className
.replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');
Here's a way to bake this functionality right into all DOM elements:
HTMLElement.prototype.removeClass = function(remove) {
var newClassName = "";
var i;
var classes = this.className.split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] !== remove) {
newClassName += classes[i] + " ";
}
}
this.className = newClassName;
}
div.classList.add("foo");
div.classList.remove("foo");
More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList
Try this:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function removeClass(ele, cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
Edit
Okay, complete re-write.
It's been a while, I've learned a bit and the comments have helped.
Node.prototype.hasClass = function (className) {
if (this.classList) {
return this.classList.contains(className);
} else {
return (-1 < this.className.indexOf(className));
}
};
Node.prototype.addClass = function (className) {
if (this.classList) {
this.classList.add(className);
} else if (!this.hasClass(className)) {
var classes = this.className.split(" ");
classes.push(className);
this.className = classes.join(" ");
}
return this;
};
Node.prototype.removeClass = function (className) {
if (this.classList) {
this.classList.remove(className);
} else {
var classes = this.className.split(" ");
classes.splice(classes.indexOf(className), 1);
this.className = classes.join(" ");
}
return this;
};
Old Post
I was just working with something like this. Here's a solution I came up with...
// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
Object.defineProperty(String.prototype,'trim', {
value: function() {
return this.replace(/^\s+|\s+$/g,'');
},
writable:false,
enumerable:false,
configurable:false
});
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
value: function(c) {
if(this.className.indexOf(c)<0) {
this.className=this.className+=' '+c;
}
return this;
},
writable:false,
enumerable:false,
configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
value: function(c) {
this.className=this.className.replace(c,'').replace(' ',' ').trim();
return this;
},
writable:false,
enumerable:false,
configurable:false
});
Now you can call myElement.removeClass('myClass')
or chain it: myElement.removeClass("oldClass").addClass("newClass");
It's very simple, I think.
document.getElementById("whatever").classList.remove("className");
try:
function removeClassName(elem, name){
var remClass = elem.className;
var re = new RegExp('(^| )' + name + '( |$)');
remClass = remClass.replace(re, '$1');
remClass = remClass.replace(/ $/, '');
elem.className = remClass;
}
var element = document.getElementById('example_id');
var remove_class = 'example_class';
element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');
I use this JS snippet code :
First of all, I reach all the classes then according to index of my target class, I set className = "".
Target = document.getElementsByClassName("yourClass")[1];
Target.className="";
document.getElementById("whatever").className += "classToKeep";
With the plus sign ('+') appending the class as opposed to overwriting any existing classes

Categories