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
?
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
?
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: