Adding a class with javascript, not a replacement

I would like to add a class to an element, rather than replacing classes that already exist.

Here is my javascript:

function black(body) {
var item = document.getElementById(body);
    if (item) {
        item.className=(item.className=='normal')?'black':'normal';
    }
}

This javascript piece replaces existing classes black. If the class is already equal black, then it changes to normal.

I would like to somehow combine the script above with the script below the script, which adds a class instead of replacing all existing classes.

var item = document.getElementById("body");
item.className = item.className + " additionalclass";
+5
source share
3 answers

Here are some simple javascript functions that you can use to manage class names in simple javascript. These functions require a bit of extra work to match only whole class names and avoid extra spaces before / after classes:

function removeClass(elem, cls) {
    var str = " " + elem.className + " ";
    elem.className = str.replace(" " + cls + " ", " ").replace(/^\s+|\s+$/g, "");
}

function addClass(elem, cls) {
    elem.className += (" " + cls);
}

function hasClass(elem, cls) {
    var str = " " + elem.className + " ";
    var testCls = " " + cls + " ";
    return(str.indexOf(testCls) != -1) ;
}

function toggleClass(elem, cls) {
    if (hasClass(elem, cls)) {
        removeClass(elem, cls);
    } else {
        addClass(elem, cls);
    }
}

function toggleBetweenClasses(elem, cls1, cls2) {
    if (hasClass(elem, cls1)) {
        removeClass(elem, cls1);
        addClass(elem, cls2);
    } else if (hasClass(elem, cls2)) {
        removeClass(elem, cls2);
        addClass(elem, cls1);
    }
}

black normal, - , :

function black(id) {
    var obj = document.getElementById(id);
    if (obj) {
        toggleBetweenClasses(obj, "black", "normal");
    }
}

: http://jsfiddle.net/jfriend00/eR85c/

"" , "" , :

function black(id) {
    var obj = document.getElementById(id);
    if (obj && !hasClass(obj, "normal")) {
        addClass(obj, "black");
    }
}
+4

// , - ( 2-3 , jfriend00).

, , , :

function toggle(id) {
    var obj = document.getElementById(id), str, len;

    if (obj) {
        str = " " + obj.className + " ";
        len = str.length;

        str = str.replace(" normal ", " ");

        if (str.length != len) {
            str += " black";
        } else {
            str = str.replace(" black ", " ");

            if (str.length != len) {
                str += " normal";
            }
        }

        obj.className = str.replace(/^\s+|\s+$/g, "");
    }
}

, , , ( ), .

. , .

DEMO

0

I don’t know if you want it or not, because the answers here seem complicated to me ... In any case, I had to add the class name without replacing the old one, so I did so.

menu.children[i].getElementsByTagName('a')[0].**classList.add('resetAfter')**;

here I used classList.add()to add classes to the anchor tag.

0
source

All Articles