2

I have multiple select elements that I need to get the same options using Javascript. They all have the same class. This code works with an id but not with class.

I tried changing getElementById to getElementsByClassName, but that doesn't seem to work. I am pretty new to Javascript and don't completely understand the difference between these two commands.

The code:

<select class="phoneNumber"></select>
<script>
phoneNumber = document.getElementById("phoneNumber");

var option = document.createElement('option'); option.text = '1234567897'; phoneNumber.appendChild(option);
var option = document.createElement('option'); option.text = '1233213211'; phoneNumber.appendChild(option);
</script>
MrVanilla
  • 357
  • 1
  • 11
  • 1
    **getElementById** will return you a single element where as **getElementsByClassName** will return array of all element with the same class. – K.D Oct 29 '15 at 08:42
  • Yes, but how do i get getElementsByClassName to work in that code? I need to replicate the select options in all selects with the class phoneNumber and it simply doesn't work changing it to getElementsByClassName. Do you have a solution to my problem K.D? – MrVanilla Oct 29 '15 at 09:03

1 Answers1

0

Using querySelector instead of getElementsByClassName solved this problem.

MrVanilla
  • 357
  • 1
  • 11
  • 1
    How does `.querySelector()` solve the problem? It will only return the first element found by the selector – Andreas Oct 29 '15 at 08:47
  • I realized that now after some more testing. Do you have a solution to this problem Andreas? – MrVanilla Oct 29 '15 at 09:02
  • 1
    https://stackoverflow.com/questions/10693845/what-does-getelementsbyclassname-return – Andreas Oct 29 '15 at 09:04
  • That is probably the right answer but I did not get it to work. Could you be kind and help me by changing my code to the correct answer? That way I'll also understand it better. – MrVanilla Oct 29 '15 at 09:13
  • https://stackoverflow.com/questions/14142677/how-to-use-getelementsbyclassname-in-javascript-function – Andreas Oct 29 '15 at 09:20