I have a psuedo element for a div. I want to make an eventListener so that when I click on the psuedo element I can get the innerHTML of the div it is attached to. Is this possible? How do I do this?
Asked
Active
Viewed 327 times
0
-
Did you try anything?.....It is better to include some of your tried code in the question.... – Mamun Dec 08 '18 at 06:39
-
No I didn't try anything. All I've been able to find is how to select the psuedo element. – icewizard Dec 08 '18 at 06:42
-
@icewizard - [This](https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin) link can help. – tomerpacific Dec 08 '18 at 06:51
-
Possible duplicate of [Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery](https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin) – tomerpacific Dec 08 '18 at 06:52
1 Answers
2
The :before
pseudo element is just that, a pseudo element. It is not a dom node and you can't attach an event listener to it specifically.
The best you can do is instead, add an event listener to the element that owns the pseudo element.
document.querySelector('#target').onclick = function(e) {
var text = document.createTextNode(this.innerHTML);
document.querySelector('#out').appendChild(text);
}
#target:before {
content: 'Click me!';
color: red;
}
<div id="target">
<p>or click here</p>
</div>
<div id="out"></div>

SpencerPark
- 3,298
- 1
- 15
- 27
-
1nitpick, but some events will actually fire on the pseudo-elements and thus will expose a `pseudoElement` property in the Event, [e.g transitionend does expose such a behavior.](https://jsfiddle.net/q0anxk8m/) – Kaiido Dec 08 '18 at 08:44
-
@Kaiido, thanks for this additional information. Although click is not one of those events, the css events (like [transition](https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent) and [animation](https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent)) do have the `pseudoElement` property. In this case you can get a handler to fire only for the events pertaining to a specific pseudo element, but the event handler still must be attached to the parent and filtered. – SpencerPark Dec 08 '18 at 19:10