leek1234
leek1234

Reputation: 470

How do I append text to the end of a select option's text using javascript?

Hi i've got a select option menu that is pulled through dynamically, where i want to add a message to certain flavours at the end of the options text to say "New" or "Staff Pick" for example.

In this instance I want to add "Staff Pick" to the end of Banana & Kiwi. How would i do this? So far I've been able to target the two flavours but not sure how i would add the copy to the end of each. Any help on this would be appreciated

document.querySelectorAll('.form-dropdown').forEach(function(select) {
  Array.from(select.options).forEach(function(option) {
    if (option.innerText.includes("Banana") || option.innerText.includes("Kiwi")) {
      // the below code is set to disabled to show the two flavours have been targeted
      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</option>
  <option value="3">Kiwi</option>
  <option value="4">Lemon</option>
</select>

Upvotes: 1

Views: 911

Answers (1)

Jamiec
Jamiec

Reputation: 136074

You've done the hard bit - just change the innerText of the element

document.querySelectorAll('.form-dropdown').forEach(function(select) {
  Array.from(select.options).forEach(function(option) {
    if (option.innerText.includes("Banana") || option.innerText.includes("Kiwi")) {
      // the below code is set to disabled to show the two flavours have been targeted
      option.innerText += " (Staff Pick)"
    }
  });
});
<select class="form-dropdown">
  <option disabled="" value="">Choose option</option>
  <option value="0">Apple</option>
  <option value="1">Banana</option>
  <option value="2">Cherry</option>
  <option value="3">Kiwi</option>
  <option value="4">Lemon</option>
</select>

Upvotes: 2

Related Questions