How do you do jQuery’s hasClass with plain ol’ JavaScript? For example,
hasClass
<body class="foo thatClass bar">
What’s the JavaScript way to ask if <body> has thatClass?
<body>
thatClass
Simply use classList.contains():
classList.contains()
if (document.body.classList.contains('thatClass')) { // do some stuff }
Other uses of classList:
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:
classList Browser Support
2.1m questions
2.1m answers
60 comments
57.0k users