Skip to content
Related Articles

Related Articles

Improve Article

How to clear all options in a dropdown box?

  • Last Updated : 27 Sep, 2019
Geek Week

Clearing the entire dropdown list is pretty easy, all we have to do is to create a button, which calls a function that performs the deletion.
Let’s look at the syntax of the deletion part:

document.getElementById("idofdropdownlist").innerHTML = "";

Here, it gets all the elements present in the given Id and clears then by assigning all the objects null, if not assigned to null, still object remains.
Approach 1: Check out the code:




<!DOCTYPE html>
<html>
  
<body>
  
    <p>Which character is your favorite guardian?</p>
      
        <select id="guardian">
            <!--dropdown list with id=guardian-->
            <option>Guardians</option>
            <option>Quill</option>
            <option>Gamora</option>
            <option>Drax</option>
            <option>rocket</option>
            <option>groot</option>
            <option>mantis</option>
        </select>
  
        <input type="button" onclick="myFunction()"
               value="Only IronMan clear them all" />
        <!––Button which avokes myFuction()-->
  
        <script>
            function myFunction() {
                //clears all the guardians with the specified id
                document.getElementById("guardian").innerHTML =
                    null;
            }
        </script>
</body>
  
</html>

Output:
output
output

Approach 2:
This process not only removes the option but also removes the dropdown box too.
Check out the code:




<html>
  
<body>
  
    <p>Which character is your favorite guardian?</p>
  
    <select id="guardian">
        <!--dropdown list with id=guardian-->
        <option>Guardians</option>
        <option>Quill</option>
        <option>Gamora</option>
        <option>Drax</option>
        <option>rocket</option>
        <option>groot</option>
        <option>mantis</option>
    </select>
  
    <input type="button" 
           onclick="myFunction()" 
           value="Only IronMan clear them all">
    <!––Button which avokes myFuction()-->
  
    <script>
        function myFunction() {
            //process the options in a loop and removes them
            document.querySelectorAll(
              '#guardian').forEach(guardian => guardian.remove())
                //here, guardian inside the for is a variable not id.
        }
    </script>
</body>
  
</html>

Output:
output
output

These methods work on all browsers.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :