Prepend to top of Option list

Viewed 82

Hi I've got a select options list where i want to prepend the options which are Out of stock to the top of the list. I've got this working but not exactly how i want it. I want it to sit under "Choose Option" as this should always be at the top, how would i do this?

document.querySelectorAll('.form-dropdown').forEach(function(select) {
  Array.from(select.options).forEach(function(option) {
    if (option.innerText.includes("Out of stock")) {
      select.removeChild(option);
      select.prepend(option);
      option.setAttribute("disabled", true);
    }
  });
});
<select class="form-dropdown">
  <option disabled="" value="">Choose option</option>
  <option value="0">Apple</option>
  <option value="1">Banana</option>
  <option value="2">Cherry - Out of stock</option>
  <option value="3">Kiwi</option>
  <option value="4">Lemon - Out of stock</option>
  <option value="5">Melon - Out of stock</option>
  <option value="6">Watermelon</option>
</select>

1 Answers

You can leave out the select.removeChild(option); as the element will be moved anyway when using .prepend(), or, as in my solution .insertBefore(). element.insertBefore(newNode,existingNode) places the newNode before the specified existingNode.

document.querySelectorAll('.form-dropdown').forEach(function(select) {
  Array.from(select.options).forEach(function(option) {
    if (option.innerText.includes("Out of stock")) {
      select.insertBefore(option,select.options[1]);
      option.setAttribute("disabled", true);
    }
  });
});
<select class="form-dropdown">
  <option disabled="" value="">Choose option</option>
  <option value="0">Apple</option>
  <option value="1">Banana</option>
  <option value="2">Cherry - Out of stock</option>
  <option value="3">Kiwi</option>
  <option value="4">Lemon - Out of stock</option>
  <option value="5">Melon - Out of stock</option>
  <option value="6">Watermelon</option>
</select>

Related