Skip to content
Advertisement

Check if class exists somewhere in parent

I want to check if a class exsits somewhere in one of the parent elements of an element.

I don’t want to use any library, just vanilla JS.

In the examples below it should return true if the element in question resides somewhere in the childs of an element with “the-class” as the class name.

I think it would be something like this with jQuery:

JavaScript

So this returns true:

JavaScript

So does this:

JavaScript

…but this returns false:

JavaScript

Advertisement

Answer

You’ll have to do it recursively :

JavaScript

Demonstration (open the console to see true)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement