Your handler should be on your select element, not on the option elements.
Try adding an onChange handler on your select element and reference the selected dropdown item on the events target.value property in your handler.
Thanks for replying, onChange does work on the select tag, but I need this event to be on the option tags, because I’m creating a list of option dynamically to list all the genres of my genres array of objects.
It seems I can’t use onClick or onChange on a <option> tag?
Did you test out my suggestion? The event object that is passed to your onChange handler should give you the value of the selected option (via event.target.value) when onChange is triggered if you attach it to the select element. It does not matter if your list of options is dynamic, it will apply to the options you have at the time your event handler is triggered.
I tested this against a slight modification of your code and it worked fine, but maybe I’m not fully understanding your question.
I ended up with another structure, I found out you can’t have event listener on <option></option> tags, if you want to read the value of the selected option element you have to add the event to the <select></select> tag with event.target.value, however this approach wouldn’t do it for me as I was not trying to get the value but the object itself. Besides, <option></option> tags are hard to style, so I used <li></li> elements instead, much easier.
Honestly I would like to create a custom and reusable dropdown component w/o using the <option> tags. I’ve seen some libraries use <div> and/or <li>, I would like to know how they do it so I can create one myself.
If by object you mean the HTML element, you will get that reference from event.target if you put the handler on the select element.
Check out this example and let me know if it’s what you’re trying to do.
It displays the target value in the DOM as well as the HTML element in the console.
It worked for my requirement. Thank you @cmccormack
If any one wants to know how onChange event works on tag please refer this link from MDN HTMLElement-change_event