Search code examples
javascriptgreasemonkey-4

What makes those two invocations of addEventListener differ, resulting in one having an effect and the other not?


I was trying to write a Greasemonkey script that hooks to onclick of a specific element. Here's the code that doesn't work (seems to be ignored silently, has no observable effect):

img = document.evaluate('//img [@title="Play / Pause"]', document.body).iterateNext()
result = img.addEventListener("click", OnPlay)

On one chat, I got a similar, but working solution:

Array.from(document.querySelectorAll('img[title="Play / Pause"]')).forEach(elem => elem.addEventListener("click", OnPlay))

Apart from one being functional and the other imperative, what made one of them work and the other one not? The console seems to give me no clues.


Solution

  • I was just poking in the dark which did contain the answer though. So, that the question does not remain answerless, I'm adding this.

    The issue apparently was that both scripts are not equivalent, and the iterateNext() only returns one element and not multiple.