Remove all options from a drop-down with JavaScript/jQuery
This post will discuss how to remove all options from a dropdown list in JavaScript and jQuery.
1. Using jQuery
jQuery has .remove() method for removing elements from the DOM. We can use it to remove all <option> from a <select> element, as shown below:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $('#pets option').remove(); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Remove All</button> |
Like the .remove() method, we can use the .empty() method to take the elements out of the DOM.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $('#pets').empty(); }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Remove All</button> |
Alternatively, you can use the .html() method to set the select element content empty.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $('#pets').html(''); }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Remove All</button> |
2. Using JavaScript
In plain JavaScript, you can get the list of all options using the querySelectorAll() method and then call JavaScript’s remove() method on each one of them.
JS
|
1 2 3 4 |
document.getElementById('submit').onclick = function() { var options = document.querySelectorAll('#pets option'); options.forEach(o => o.remove()); } |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Remove All</button> |
Another simple and fairly efficient solution is to use the browser’s innerHTML property, which is also being used by the jQuery’s .html() method.
JS
|
1 2 3 |
document.getElementById('submit').onclick = function() { document.querySelector('#pets').innerHTML = ''; } |
That’s all about removing all options from a drop-down in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)