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 »
- Store the select element to a variable named myVariable using the document.getElementById() method.
- myVariable will return all the options of the select element as a NodeList.
- Select a specific option using it's indexing number. For example, myVariable[1] that returns the second option.
- setAttribute() method is used to add a new attractive to a specific element.
Pdf
Save
Listen
How to add selected attribute to option using JavaScript
0
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 e…
asked
Apu
0 answers
2915
In this article,you will learn how to add selected attribute to option using JavaScript . …
Answer Link
answered
Apu