Search code examples
javascriptselectdropdownselector

How I can get all the values of select tag if 'id' of select tag is dynamic?


Problem: I have dropdown menus (around 10 on one page and each have different id ). I am trying to automate those control fields, where I need to set the value of dropdown menu and I am trying to implement a generic solution for all dropdown menu.

For Example: For given dropdown menu, I want to set its value to Korean (ECU-KR).

My Approach: To automate this dropdown, I am trying to get all the values of select tag and iterating each to compare with the require value (that I want to set in dropdown menu(Korean (ECU-KR))). But I stuck here.....

Need Help In:

  1. How to get 'id' of select tag ?

  2. If I get id, then How I can get all the values of a particular select tag ?

enter image description here

enter image description here


Solution

  • Assuming you know the value you want to set – and with the assumption that only one <option> element exists with that value – I’d suggest not worrying about the <select> element and instead focus on the <option>:

    // select the <option> element by its value attribute:
    let option = document.querySelector('option[value="ECU-KR"]'),
        // if you still have need of the <select> element:
        select = option.closest('select');
    // set the selected property of the <option>:
    option.selected = true;