I have different select elements for changing the size of different products, each size has a different price. I can do it with one select element using querySelector but it won't work with querySelectorAll.
Here's my code for changing only one select element:
const price = document.querySelector(".price");
const select = document.querySelector(".select");
select.addEventListener("change", () => {
price.innerText = select.options[select.selectedIndex].value;
});
<div>
<p class="price">$15</p>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$20">40cmx40cm</option>
<option value="$30">30cmx40cm</option>
<option value="$50">50cmx50cm</option>
</select>
</div>
I've tried for loops and forEach but nothing worked (probably cause i'm doing it wrong). Any help would be appreciated. I'm losing my mind.
You can accomplish this by using "event delegation" where you set up just one handler on an element that is a common ancestor to all the
selectelements you wish to handle events on. The event will originate at theselectbut not be handled there and will "bubble" up to the ancestor you choose. Then you handle the event at that ancestor and use theevent.targetthat will be accessible in the handler to reference the actual element that triggered the event and relative DOM references to reference thepelement you need to update.The benefit here is that you only set up one handler (which saves on memory and performance) and the code is simplified. Also, you can add new
selectstructures without having to alter the handling code at all.