1

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.

d33tah
  • 10,999
  • 13
  • 68
  • 158
  • 1
    These two implementation attempts don't seem equivalent. The first would only add a query listener one image. The other one listens on every image element. Is it perhaps an unexpected image element that is being fetched here? Also: I am not very familiar with the evaluate method, but the inputs look off compared to the documentation https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate. The iterateNext() seems to do what you'd expect though. – Timothy L Gillespie Aug 20 '22 at 20:39
  • 1
    @TimothyLGillespie you're right! They'd only be equivalent if there was exactly one button matching those criteria, but that's not the case. Mystery solved, thanks! – d33tah Aug 20 '22 at 20:41

1 Answers1

1

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.