Richard Bustos
Richard Bustos

Reputation: 35

Adding CSS classes to an element using JavaScript

<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.

Upvotes: 4

Views: 7725

Answers (2)

Phrogz
Phrogz

Reputation: 303224

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

Upvotes: 4

user1823761
user1823761

Reputation:

Working FIDDLE Demo

Try this:

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

var foo = document.getElementById('foo');
addClass(foo, 'a');
addClass(foo, 'b');

Upvotes: 4

Related Questions