23

Example HTML:

<div id="foo" class="class_one"></div>

How can I add the class class_two without replacing class_one?

end result:

<div id="foo" class="class_one class_two"></div>
0

4 Answers 4

65

See deekshith's answer below if you only need to support new browsers

Standard javascript:

document.getElementById('foo').className += ' class_two'

or JQuery:

$('#foo').addClass('class_two');
Sign up to request clarification or add additional context in comments.

Comments

21

You may use jQuery.

$('#YourElement').addClass('YourClass'); //add

$('#YourElement').removeClass('YourClass'); //remove

$('#YourElement').toggleClass('YourClass'); //toggle

Or Javascript, if you wish.

document.getElementById('id').classList.add('YourClass'); //add
document.getElementById('id').classList.remove('YourClass'); //remove

1 Comment

classList is available on most modern browsers monhttp://caniuse.com/#feat=classlist
18

A better way to add a class would be to use Element.classList.add():

document.getElementById('foo').classList.add("class_two");

Comments

3

You can make life easier with a couple of helper functions:

function addClass(el, className) {
  var classes = el.className.match(/\S+/g) || [];  

  if (!hasClass(el, className)) {
    classes.push(className);
  }
  el.className = classes.join(' ');
}

function hasClass(el, className) {
  var re = new RegExp('(^|\\s+)' + className + '(\\s+|$)');
  return re.test(el.className);
}

addClass(document.getElementById('foo'), 'bar')

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.