Skip to content
Advertisement

Selecting and removing a html select option without selecting by index or ID, using vanilla JavaScript

I need to remove an option on a select box, and I’ve figured out a potential solution in the code below, but it doesn’t feel particularly ‘safe’ (if another developer decided to add an option to the backend, the option will re-appear). Is there a better way of achieving this without resorting to jQuery?

(function (){
    var parent = document.getElementById("MediaCategory");
    var child = parent.children[8];

    if(parent.options[8].text === "Archive") {
        parent.removeChild(child);
        }
})();

As I see it, I’m selecting the ID of the select form element and storing it in a variable, I’m also storing the 9th child of the select, which is the option I want to remove.

Then for extra safety, I’ve stuck in an if statement to double check that the option I’m selecting has the correct text.

Is there something simple I’m missing that I could add? I couldn’t find a way to select the option by the value alone by scouring the web, just by class name or ID.

Advertisement

Answer

Something like this?

(function (){
    var parent = document.getElementById("MediaCategory");

    for(var i=0; i< parent.children.length; i++){
        var child = parent.children[i];

        if(child.text === "Archive") {
            parent.removeChild(child);
        }
    }       
})();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement