Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

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

<body class="foo thatClass bar">

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

1 Answer

0 votes
by (13.1k points)

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 ) 

Interested in full-stack development? Check out the full-stack development course from Intellipaat.

Related questions

Browse Categories

...