Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "hasClass" function with plain JavaScript?

Tags:

javascript

dom

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?

like image 472
Kyle Cureau Avatar asked Feb 23 '11 00:02

Kyle Cureau


People also ask

What is Javascript hasClass?

The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".


2 Answers

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

like image 194
Damien Avatar answered Sep 28 '22 04:09

Damien


You can check whether element.className matches /\bthatClass\b/.
\b matches a word break.

Or, you can use jQuery's own implementation:

var className = " " + selector + " "; if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 )  

To answer your more general question, you can look at jQuery's source code on github or at the source for hasClass specifically in this source viewer.

like image 27
SLaks Avatar answered Sep 28 '22 04:09

SLaks