Tuesday, December 30, 2014

<SELECT> with <OPTGROUP> doesn't have .remove() implemented [IE9+]

I found this semi-official link (because it's part of Microsoft.com, but a forum of sorts)

TL;DR - my way
var opts = selectControl.options;//I was doing other stuff with the options
opts[deleteIndex].parentElement.removeChild(opts[deleteIndex]);
 
The above was modified based on what was contributed by Abhisek Gupta:
selectControl.options[deleteIndex].parentElement.removeChild(selectControl.options[deleteIndex]); 
The explanation was something about .remove() not being in ECMAScript to begin with...

The root of the solution is to use .removeChild() but this one-liner is slightly more elegant:
  1. retrieve the HTMLOptionElement from its HTMLSelectElement;
  2. call its parent; in other words, our offending HTMLOptGroupElement;
  3. instruct for it to removeChild;
  4. pass in part 1. as argument to part 3.
You can alternatively check this other link.

Additionally, I wanted to detect for the presence of HTMLOptGroupElement. I added this to check:
function hasOptGroups(selObj) {
    if(selObj instanceof HTMLSelectElement) {
        var selCN = selObj.childNodes;
        if(selCN && selCN.length > 0) {
            for(var x=0;x<selCN.length;x++) {
                if(selCN[x] instanceof HTMLOptGroupElement) {
                    return true;
                    break;
                }
            }
        }
    }
    return false;
}



This way, I still get to use the original .remove() if there are no <OPTGROUP>'s present.

No comments:

Post a Comment