Add a class to a DIV with javascript

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>

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

Standard javascript:

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

or JQuery:


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

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


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)) {
  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')

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Backbone.View "el" confusion

Similar Posts