Skip to content

How to check if an HTML element has any of a list of classes

Sometimes we have a body with a bunch of HTML classes and we want to initialize a component or run a function when either of those classes exist.

For example, let’s say our <body> tag gets populated whenever a module is included in that particular page:

<body class="resource-template-default single single-resource postid-476 wp-embed-responsive  single-page-name">

We can run:

const classes = ['has-posts-list', 'single-resource', 'single-post']
if (classes.some((i) => document.body.classList.contains(i))) {
	initFunction();
}