Olyvar
Olyvar

Reputation: 39

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.

Upvotes: 0

Views: 119

Answers (3)

Ash
Ash

Reputation: 2108

var parent = document.getElementById("MediaCategory");
for (var i=0; i<parent.options.length;i++) {
	if (parent.options[i].text == 'Archive') {
		parent.remove(i);
                break;
	}	
}

Upvotes: 0

Jonathon Blok
Jonathon Blok

Reputation: 749

I would loop through all options, and remove the option when you find it. The break statement will stop the loop once it's found the option to remove.

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

    for (var i=0; i<parent.children; i++){
        if (parent.children[i].text === "Archive") {
            parent.removeChild(parent.children[i]);
            break;
        }
    }
})();

Upvotes: 0

Philip Bijker
Philip Bijker

Reputation: 5115

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);
        }
    }       
})();

Upvotes: 1

Related Questions