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>
7
  • 1
    If you're just setting text, use textContent instead of innerHTML Commented Sep 19, 2014 at 13:24
  • possible duplicate of How to Change The Selected Option of HTML Select Element? Commented Sep 19, 2014 at 13:25
  • @NickDugger really? What about IE8? :) Commented Sep 19, 2014 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. Commented Sep 19, 2014 at 13:27
  • 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. Commented Sep 19, 2014 at 15:08

3 Answers 3

37

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

document.getElementsByName('stuff')[0].options[0].innerHTML = "Water";
Sign up to request clarification or add additional context in comments.

3 Comments

shouldn't it be: document.getElementsByName('stuff').options[0].innerHTML = "Water";
@AndreNel Nope, getElementsByName returns an array-like object, so you want to pick the first one in that array :)
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... :)
5

You can try this:

 $('select[name=stuff] option:first').html("abcd");

2 Comments

OP did not ask for jQuery, nor does this question have the jQuery tag.
Same question and I want to use to jQuery - thanks for contributing.
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>

1 Comment

also works : document.getElementById("first").text= "Water";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.