Applescript / Javascript : select menu

applescriptjavascript

I'm filling a webpage using Applescript / Javascript,

one of them is a dropdown menu, which I fill with this code :

document.querySelector('select#reasonPopUpButton').value = '18';

the issue is the index change time to time.

Can I select the good menu using the title instead of the index?

Here what I tried so far :

tell application "Safari"
    do JavaScript "document.querySelector('select#reasonPopUpButton').value = 'Unauthorized purchase';" in current tab of window 1

end tell

Best Answer

You can filter the list of options for one with the text you're looking for, then select that one. This can be achieved with the following JavaScript:

Array.from(document.querySelector('select#reasonPopUpButton').children)
  .find(el => el.textContent == "Unauthorized purchase")
  .selected = true;