25

Im trying to modify the text of the first select option via javascript. But it empties the entire select option

 <select name='stuff'>
      <option value="a"> Pepsi </option>
      <option value= "b"> Juice </option>
 </select>


<script type="text/javascript">
    document.getElementsByName('stuff')[0].innerHTML = "Water";
</script>
meWantToLearn
  • 1,691
  • 2
  • 25
  • 45
  • 1
    If you're just setting text, use `textContent` instead of `innerHTML` – ndugger Sep 19 '14 at 13:24
  • possible duplicate of [How to Change The Selected Option of HTML Select Element?](http://stackoverflow.com/questions/7373058/how-to-change-the-selected-option-of-html-select-element) – laaposto Sep 19 '14 at 13:25
  • @NickDugger really? What about **IE8**? :) – Roko C. Buljan Sep 19 '14 at 13:25
  • @RokoC.Buljan Depends on his target platform, but then you'd use a combination of innerText and textContent, but innerHTML is hardly appropriate here. – ndugger Sep 19 '14 at 13:27
  • @NickDugger can you explain why innerHTML is hardly appropriate? And why than a fallback from `textContent` to `innerHTML`? – Roko C. Buljan Sep 19 '14 at 13:28
  • @RokoC.Buljan innerHTML does trigger a reflow and textContent does not work with IE8>. I'd go with innerText for this one but from a user perspective; he/she won't notice the difference. – Frinsh Sep 19 '14 at 13:51
  • 1
    @Frinsh Just for the record, FF does not support innerText, so you would have to do a short polyfill, in which case you should polyfill textContent, and not the other way around. – ndugger Sep 19 '14 at 15:08

3 Answers3

36

You want to read from the options collection and modify the first element in there:

document.getElementsByName('stuff')[0].options[0].innerHTML = "Water";
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 2
    shouldn't it be: document.getElementsByName('stuff').options[0].innerHTML = "Water"; – Andre Nel May 15 '19 at 08:36
  • @AndreNel Nope, `getElementsByName` returns an array-like object, so you want to pick the first one in that array :) – CodingIntrigue May 15 '19 at 08:37
  • Ah of course I see its using getElementsByName I was thinking of getElementById... so I was thinking: document.getElementById('stuff').options[0].innerHTML = "Water"; ... which get one select but on Id and not name rather than what was given: document.getElementsByName('stuff')[0].options[0].innerHTML = "Water"; ... sorry... :) – Andre Nel May 15 '19 at 08:42
5

You can try this:

 $('select[name=stuff] option:first').html("abcd");
Satya Ranjan Sahoo
  • 1,086
  • 7
  • 24
0

I think this should work:

 <select name='stuff'>
          <option id="first" value="a"> Pepsi </option>
          <option value= "b"> Juice </option>
     </select>


    <script type="text/javascript">
        document.getElementById("first").innerHTML = "Water";
    </script>
Florin Pop
  • 5,105
  • 3
  • 25
  • 58