We can use JavaScript to set select to the first option by using the getElementById() and getElementsByTagName() methods and targeting the value property.
document.getElementById("select-element").value = document.getElementById("select-element").getElementsByTagName('option')[0].value;
Let’s see an example of this below.
Lets say we have the following HTML:
Change select to first option
In this example, the selected option to start will be the middle option, Bus. We can put our code above to use to make it so that when the user clicks the button, the selected option will be changed to the first option, Car.
We will create a function that runs this code when the user clicks our button.
Here is the JavaScript code we will need:
function changeSelect(){
document.getElementById("select1").value = document.getElementById("select1").getElementsByTagName('option')[0].value;
};
Try it out below:
Code Output:
Full Code:
Change select to first option
Using JavaScript to Set Select to the Last Option
To set Select to the last option, we can use our code from above, just change 0 to the length of our select element.
document.getElementById("select1").length;
Let’s add this code to our code from above:
document.getElementById("select1").value = document.getElementById("select1").getElementsByTagName('option')[document.getElementById("select1").length-1].value;
Let’s see this in action below:
Code Output:
Full Code:
Change select to last option
Using JavaScript to Set Select to a Specific Option
To set the Select to a specific option, in this case the middle option, Bus, we can change the number from our code above.
document.getElementById("select3").value = document.getElementById("select3").getElementsByTagName('option')[1].value;
Let’s see this in action below:
Code Output:
Full Code:
Change select to middle option
Hopefully this article has been useful to help you understand how to use JavaScript to set select to the first option.