2

I have an amazon website URL here: https://www.amazon.com/dp/B07DKCQSQ5

I'm trying to write some javascript code so that I can select one of the size options in the size dropdown enter image description here

I'm trying to get a size option selected by opening the devtools console on the page and running some javascript code in the console.

This code: document.querySelector('#native_dropdown_selected_size_name') grabs the correct dropdown, and I can view all the nested option elements.

I tried to get all the nested option elements and click on with this code:

document.querySelector('#native_dropdown_selected_size_name').querySelectorAll('option')[3].click() but it just returns undefined and nothing gets selected?

I'm trying to write the code in pure javascript (no jquery)

Martin
  • 1,336
  • 4
  • 32
  • 69
  • Does this answer your question? [How do I change an HTML selected option using JavaScript?](https://stackoverflow.com/questions/10911526/how-do-i-change-an-html-selected-option-using-javascript) – MauriceNino Nov 04 '20 at 08:33
  • If you click that select button, the box that pops up is not a –  Nov 04 '20 at 08:38

1 Answers1

0

If you need to trigger the event that change the page content then you have to simulate the click event like so:

let dropdown = document.getElementById("native_dropdown_selected_size_name");
let dropdown_element = document.getElementById("native_dropdown_selected_size_name_1");
// change the id "native_dropdown_selected_size_name_1" using the number of the item you want to be selected

let evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
dropdown.dispatchEvent(evt);
dropdown_element.dispatchEvent(evt);
Fantantonio
  • 377
  • 4
  • 15