What is the "hasClass" function with plain JavaScript?

Kyle picture Kyle · Feb 23, 2011 · Viewed 431.4k times · Source

How do you do jQuery’s hasClass with plain ol’ JavaScript? For example,

<body class="foo thatClass bar">

What’s the JavaScript way to ask if <body> has thatClass?

Answer

Damien picture Damien · May 2, 2013

Simply use classList.contains():

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

Other uses of classList:

document.body.classList.add('thisClass');
// $('body').addClass('thisClass');

document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');

document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');

Browser Support:

  • Chrome 8.0
  • Firefox 3.6
  • IE 10
  • Opera 11.50
  • Safari 5.1

classList Browser Support