Event listener on a CSS pseudo-element, such as ::after and ::before?

I have a div element with a CSS pseudo-element ::before used as a close button (instead of using an actual button). How do I apply an event listener to only the pseudo-element?

HTML

<div id="box"></div>

CSS

#box:before
{
 background-image: url(close.png);
 content: '';
 display: block; 
 height: 20px;
 position: absolute;
 top: -10px;
 right: -10px; 
 width: 20px;
}

#box
{
 height: 100px;
 width: 100px;
}

Was looking for a solution and found this thread. Now want to share my workaround:

CSS

element { pointer-events: none; }
element::after { pointer-events: all; }

JS

element.addEventListener('click', function() { ... });

This works if you don't need any pointer events on element. Check it in action.


No. The pseudo-element does not exist in the DOM so it has no HTMLElementNode object representing it.