javascripthtmldrop-down-menugetelementsbytagnamequeryselector

An Array inserted via Html tag does not give me the same vlist in multiple cells


Problem code that takes a single array and through the select command of the html it calls me in more cells of the same list, but I tried all the getElement or query, as you can see, only the first cell goes.

Only entering the document.getElementById does the first cell work.



<select id="ku">
    <option>Choose a number</option>    
</select>

<select id="ku">
    <option>Choose a number</option>    
</select>

<select id="ku">
    <option>Choose a number</option>    
</select>


<script>
   
    var select = document.querySelector("select");
    var options = ["kurs1", "Kurs2", "Kurs3", "Kurs4", "Kurs5"];

    for(var i = 0; i < options.length; i++) {
        var opt = options[i];
        var kurse = document.createElement("option");
        kurse.textContent = opt;
        kurse.value = opt;
        select.appendChild(kurse);
}
</script>


Obviously the ids or classes cannot be entered the same, I tried to enter the tag name etc... nothing.

I'm desperate and just starting out with JS. I hope you can help me understand why, thank you.


Solution

  • Use a class instead of duplicating ids. document.querySelectorAll can be used to obtain all elements matching a selector.

    const options = ["kurs1", "Kurs2", "Kurs3", "Kurs4", "Kurs5"],
          selects = document.querySelectorAll('select.ku');
    for (const option of options)
      for (const select of selects)
        select.add(new Option(option));
    <select class="ku">
        <option>Choose a number</option>    
    </select>
    <select class="ku">
        <option>Choose a number</option>    
    </select>
    <select class="ku">
        <option>Choose a number</option>    
    </select>