1

I am trying to reverse the order of font select options when I click on a button. Everything I've seen online is using jquery, is there any way I can do it with just js?

<button class="gray" type="button" onclick="sortFont();" > click </button>
<select id="fontMenu" >
   <option value="Arial">Arial</option>
   <option value="Times New Roman">Times New Roman</option>
</select>
Collin Hurst
  • 63
  • 10
  • I know you wanted only JavaScript but here is an accepted answer for jQuery if you are interested: https://stackoverflow.com/questions/1394020/jquery-each-backwards – Syfer Nov 05 '17 at 23:11

1 Answers1

6

Here I just get the options, place in an array. reverse. and then add them back.

document.querySelector("button").onclick = () => {
  const fontMenu = document.querySelector("#fontMenu");
  const options = Array.from(fontMenu.querySelectorAll("option"));
  options.reverse();
  options.forEach((o) => fontMenu.appendChild(o));
}
<button class="gray" type="button" > click </button>
<select id="fontMenu" >
   <option value="Arial">Arial</option>
   <option value="Times New Roman">Times New Roman</option>
</select>
Keith
  • 22,005
  • 2
  • 27
  • 44