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

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

Related

execute function from a string llike this "mystring".truncate(5) [duplicate]

I'd like to be able to say something like this in javascript :
"a".distance("b")
How can I add my own distance function to the string class?
You can extend the String prototype;
String.prototype.distance = function (char) {
var index = this.indexOf(char);
if (index === -1) {
alert(char + " does not appear in " + this);
} else {
alert(char + " is " + (this.length - index) + " characters from the end of the string!");
}
};
... and use it like this;
"Hello".distance("H");
See a JSFiddle here.
String.prototype.distance = function( arg ) {
// code
};
Minimal example:
No ones mentioned valueOf.
==================================================
String.prototype.
OPERATES_ON_COPY_OF_STRING = function (
ARGUMENT
){
//:Get primitive copy of string:
var str = this.valueOf();
//:Append Characters To End:
str = str + ARGUMENT;
//:Return modified copy:
return( str );
};
var a = "[Whatever]";
var b = a.OPERATES_ON_COPY_OF_STRING("[Hi]");
console.log( a ); //: [Whatever]
console.log( b ); //: [Whatever][Hi]
==================================================
From my research into it, there is no way to edit the string in place.
Even if you use a string object instead of a string primitive.
Below does NOT work and get's really weird results in the debugger.
==================================================
String.prototype.
EDIT_IN_PLACE_DOES_NOT_WORK = function (
ARGUMENT
){
//:Get string object:
var str = this;
//:Append Characters To End:
var LN = str.length;
for( var i = 0; i < ARGUMENT.length; i++){
str[LN+i] = ARGUMENT[ i ];
};
};
var c = new String( "[Hello]" );
console.log( c );
c.EDIT_IN_PLACE_DOES_NOT_WORK("[World]");
console.log( c );
==================================================
after years (and ES6) … we have a new option how to do this:
Object.defineProperty( String.prototype, 'distance', {
value: function ( param )
{
// your code …
return 'counting distance between ' + this + ' and ' + param;
}
} );
// ... and use it like this:
const result = "a".distance( "b" );
console.log(result);
You could do this:
String.prototype.distance = function (){
//your code
}
Using prototype to add you own function to string is called a prototype I created small JavaScript code that can select elements and change its innerHTML
var dom; //you can replce this to be $ just like jQuery
dom = function(elm) {
if(typeof elm === "object") {
// already done example
//typeof document.getElementById('id') will be object
return [elm];
} else {
return document.querySelectorAll(elm);
}
} // Returns elements by all css selector eg
// .class #id id p id > p id ~ p in short any css selectors
Object.prototype.text = function(txt) { //object prototype as NodeList returned would be object or maybe displayed as [Object NodeList]
var i = 0; //loop through the elements
for(i; i < this.length; i++) {
this[i].innerHTML = txt;
}
// in this function this refers to object that this function is passed on
};
dom('.classh').text('Changed for elements with classh');
dom('#heading').text('Changed for elements with id heading'); //examples

.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, '');
}
}

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.

How to add/remove a class in 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

replace class value with javascript

I would like to replace abcName with xyzName?
<tr>
<td>
<b class="abcName">Bob</b>
</td>
</tr>
Using this, but on page load nothing changes:
var bobo = document.getElementsByTagName("td");
function user(a, b, c) {
try {
if (bobo[c].innerHTML.match('>' + a)) {
bobo[c].className = b;
}
} catch (e) {}
}
function customs() {
for (i = 0; i < bobo.length; i++) {
classChange("Bob", "xyzName", i);
}
}
setInterval("customs()", 1000);
Although I'm not real sure if what you're doing with the interval and whatnot is the best approach, you can:
var tidi = document.getElementsByTagName("td");
function changeStyleUser(a, b, c) {
try {
if (tidi[c].children[0].innerHTML.indexOf(a) === 0) {
tidi[c].className = b;
}
} catch (e) {}
}
function customizefields() {
for (i = 0; i < tidi.length; i++) {
changeStyleUser("Bob", "xyzName", i);
}
}
setInterval("customizefields()", 1000);
http://jsfiddle.net/zBmjb/
Note, you also had the wrong function name in your for loop as well.
If you use jQuery, this would be MUCH simpler.
EDIT
Using jQuery:
function customizefields(a) {
$('td b').each(function(){
if ($(this).text().indexOf(a) === 0) {
this.className = 'xyzName';
}
});
}
setInterval(function(){customizefields('Bob')}, 1000);
http://jsfiddle.net/zBmjb/1/
Also, note the use of the anonymous function instead of using a string in setInterval(). This allows you to not use eval(), which is considered expensive and potentially harmful.
EDIT 2
If you wanted to pass in a list of name and class associations, you could use an array with objects, like so:
function customizefields(arrNames) {
$('td b').each(function(){
for (var i = 0; i < arrNames.length; i++) {
if ($(this).text().indexOf(arrNames[i].name) === 0) {
this.className = arrNames[i].class;
}
}
});
}
var namesToChange = [
{'name':'Bob','class':'Bob'},
{'name':'Bert','class':'Bert'},
{'name':'Jeff','class':'Jeff'}
];
setInterval(function(){customizefields(namesToChange)}, 1000);
http://jsfiddle.net/zBmjb/4/
It feels messy though, since it searches for all selected nodes, then for each found, loops over the current node for each name looking for a matched value, all while doing this once a second. The cleaner approach would be to see if the name value from the current node was found:
function customizefields(objNames) {
$('td b').each(function(){
name = $(this).text();
if (name.indexOf(" ") != -1) {
name = name.substring(0, name.indexOf(" "));
}
if (objNames[name]) {
this.className = objNames[name];
}
});
}
var namesToChange = {
'Bob':'Bob',
'Bert':'Bert',
'Jeff':'Jeff'
};
setInterval(function(){customizefields(namesToChange)}, 1000);
http://jsfiddle.net/zBmjb/5/
EDIT 3
If you need multiple values, you can make the value for the object an object as well.
function customizefields(objNames) {
$('td b').each(function(){
name = $(this).text();
if (name.indexOf(" ") != -1) {
name = name.substring(0, name.indexOf(" "));
}
if (objNames[name]) {
this.className = objNames[name].class;
this.style.backgroundImage = "url(" + objNames[name].img + ")";
}
});
}
var namesToChange = {
'Bob':{'class':'Bob','img':'bobspic.jpg'},
'Bob':{'class':'Bert','img':'Bertphoto.jpg'},
'Bob':{'class':'Jeff','img':'jeff.jpg'}
};
setInterval(function(){customizefields(namesToChange)}, 1000);
Grab the element you want to change (can do this multiple ways, in this example i used ID).
var x = document.getElementById( 'id-of-my-element' );
x.className = 'b';
To remove a class use:
x.className = x.className.replace(/\bCLASSNAME\b/,'');
Hope this helps.
Change this line:
classChange("Bob", "xyzName", i);
to this:
changeStyleUser("Bob", "xyzName", i);
Your script will work fine then. Do yourself a favor and use a debugger. :-)
if (tidi[c].innerHTML.search("class=\"abcName\"")>=0) {
tidi[c].children[0].className = b;
}

Categories