4
<body>
    <div id="foo"></div>
    <button onclick ="addClass(el,'Test') ">click</button>
</body>

<script>
    function addClass(element, myClass) {

         element.className = myClass; 
}
    var el = document.getElementById('foo');
</script>

I would like to add more more classes without the previous class being removed.

2 Answers 2

4

Working FIDDLE Demo

Try this:

function addClass(element, myClass) {
    element.className += ' ' + myClass; 
}

var foo = document.getElementById('foo');
addClass(foo, 'a');
addClass(foo, 'b');
Sign up to request clarification or add additional context in comments.

2 Comments

OK, +1 for that sweet kbd demo style :) I'm totally stealing it :)
@Phrogz It's yours... :).
4

CSS classes are space delimited in the attribute, so:

function addClass(element, myClass){
   element.className += ' '+myClass;
}

Or, for modern browsers, use classList API:

function addClass(element, myClass){
   element.classList.add(myClass);
}

…which you can even polyfill for older browsers.

If you are not using classList and wanted to ensure that your class attribute has only one instance of a given class in the string, you can remove it first (totally unnecessary but for OCD):

var re = new RegExp( "(?:^|\\s)"+myClass+"(?:\\s|$)", 'g' );
el.className = el.className.replace(re, '');

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.