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 meme</button> 
   <script>
     function myFun(){
       document.getElementById("element")[1].setAttribute('selected','selected');
     }
   </script>
  
Try it Yourself »