5

I would like the ability to add a class to an element and not replace what classes are already there.

Here is my javascript so far:

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

That piece of javascript replaces the existing classes with black. If the class already is black then it is changed to normal.

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

var item = document.getElementById("body");
item.className = item.className + " additionalclass";
1

3 Answers 3

4

Here are several plain javascript functions you can use for manipulating class names in plain javascript. It takes a little extra work in these functions to match whole class names only and avoid any extra spaces before/after classnames:

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);
    }
}

If you wanted to toggle between the black and normal classes without affecting any other classes on the specified object, you could do this:

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

Working example here: http://jsfiddle.net/jfriend00/eR85c/

If you wanted to add the "black" class unless "normal" was already present, you could do this:

function black(id) {
    var obj = document.getElementById(id);
    if (obj && !hasClass(obj, "normal")) {
        addClass(obj, "black");
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

Such a great resource to have if for instance you're unable to use jQuery, or prototype.
The toggle code seems to be what I need, but having some trouble setting it up. This is the code I have now: function black(body) { var obj = document.getElementById(body); if (obj) { toggleBetweenClasses(obj, 'normal', 'black'); } }
My body html: <body id="body" class="normal"> and my link: <a href="javascript:black('body');">link</a>
@davecave - It works for me here: jsfiddle.net/jfriend00/eR85c. You'd have to show me your working page for me to know what error you have.
@davecave - FYI, you don't need an ID on the body tag. You can always fetch it with document.body.
|
0

In case you are not going to add/remove/toggle classes that much, I would consider using something like the code below (instead of adding 2-3 functions like jfriend00's answer).

So here is the alternative for the ones that don't like to have many functions that will not use that frequently:

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

It basically stores the length, tries to replace, checks if it removed the class (by comparing old and new lengths) then applies the necessary changes.

Note: it will toggle the classes perfectly with the condition that you should not have the two classes at the same time at the beginning.

DEMO

2 Comments

I think this has a problem if the classname starts out "one normal two" because your replace makes it into "onetwo" and you end up with 'onetwo black".
@jfriend00 you are right, it should be replaced with a space. Also I need to trim spaces (updating...)
0

I don't know if this is what you want or not because the answers here seems complicated to me...Anyway I needed to add class name without replacing the old one, so this is how I did it..

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

here i used classList.add() to append classes into anchor tag.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.