Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu June 03, 2023 . #Element . #HowTo

How to add selected attribute to option using JavaScript

In this article,you will learn how to add selected attribute to option using JavaScript. We will set selected attribute to an option of HTML select element using setAttribute method.

add selected attribute to option using JavaScript
   <select id="element">
     <option>option 1</option>
     <option>option 2</option>
     <option>option 3</option>
     <option>option 4</option>
   </select>
      <button onclick="myFun()">click me</button> 
   <script>
     function myFun(){
       document.getElementById("element")[1].setAttribute('selected','selected');
     }
   </script>
Try it Yourself »
  1. Store the select element to a variable named myVariable using the document.getElementById() method.
  2. myVariable will return all the options of the select element as a NodeList.
  3. Select a specific option using it's indexing number. For example, myVariable[1] that returns the second option.
  4. setAttribute() method is used to add a new attractive to a specific element.
save
listen
AI Answer
Write Your Answer
loading
back
View All