Sassan Sassan - 3 months ago 7x
Javascript Question

Querying pseudo classes of an element in pure Javascript

I know I can check some pseudo classes' state with JQuery (like isHovered) and I know I can check an element has a particular pseudo class by running querySelector (/querySelectorAll) on its parent node.

The first is totally useless for me cause I'm not gonna use JQuery and JQuery doesn't have a

method for the pseudo class I need to query.

The second solution seems dirty, I mean if it's a property of an object (object being the Dom element) I should be able to get it in a straightforward way not by running q function on its parent node. What if my element doesn't have a parent node (you may question the possibility of an element without parent node that has pseudo classes. It may or may not be possible right now in a browser, but theoretically it's possible, maybe in a virtual Dom, or in a future implementations of browsers, idk.).

All I want is something like
element.hasPseudoClass("<the class>")
or any other convenient way to query pseudo classes of an element. I didn't find something straight forward.


You can use


var box = document.getElementById("box");
var msg = document.getElementById("msg");

setInterval(() => msg.textContent = box.matches(':hover') ? "in" : "out", 1000);
<div id="box" style="width: 100px; height: 100px; background-color: red; "></div>
<div id="msg"></div>

See the MDN documentation.