Search code examples
javascriptcsspseudo-element

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;
}

Solution

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