A structure <a><img></img></a>
(potentially more deeply nested) is generated dynamically (for simplicity assume this is the only content on the page). I want to listen to a click event on the a
element. Since it's dynamically generated, I have to attach the listener to the document and then check event.target
. However, since the element I'm interested in has a descendant, event.target
only points to the image. How can I do this?
Asked
Active
Viewed 51 times
0

Dariush
- 463
- 3
- 12
-
Look at its parent? – SLaks Nov 22 '17 at 01:25
-
I think I used an oversimplified example, so I clarified a bit. I don't know how deep the structure goes and would like a general solution "check if any element in the DOM branch matches the selector". I can manually go up the tree and check every element, but this seems rather inefficient and not particularly pretty. – Dariush Nov 22 '17 at 01:29
-
You need to walk up the tree with a loop. – SLaks Nov 22 '17 at 01:31
-
can't you get the parent element from the code that generates it, or add specific class/name to the parent nodes? There is no parent CSS selector https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector?answertab=active#tab-top – Slai Nov 22 '17 at 01:37
-
@SLaks Hm, all right. A bit disappointing that there's nothing better than the bruteforce solution, but I'll trust your credentials. I think proper etiquette here is for you to format the comment as an answer so I can accept it. – Dariush Nov 22 '17 at 01:39
1 Answers
0
You need to loop upward through the target's parents until you find a matching element.
You can write a findAncestor(callback)
function to make this cleaner.
Or you can use the Element.matches()
method (but beware of browser support).

SLaks
- 868,454
- 176
- 1,908
- 1,964
-
1The [`.closest()` method](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest) (with or without polyfill as appropriate) may help here rather than writing a custom `findAncestor()` function. – nnnnnn Nov 22 '17 at 01:52
-
By the way, how do browsers handle such cases of images in links when the image is clicked? Do they loop upwards like this? – Dariush Nov 22 '17 at 01:59