Remove duplicate elements from a drop down list using javascript

前端 未结 2 649
旧时难觅i
旧时难觅i 2021-01-23 05:10

This is the dropdown list box. I want to remove the duplicate \"Apple\" using javascript.


                        
    
提交评论

  • 2021-01-23 05:35

    In ES3 POJS you could do this.

    Javascript

    function removeDuplicateOptions(selectNode) {
        if (typeof selectNode === "string") {
            selectNode = document.getElementById(selectNode);
        }
    
        var seen = {},
            options = [].slice.call(selectNode.options),
            length = options.length,
            previous,
            option,
            value,
            text,
            i;
    
        for (i = 0; i < length; i += 1) {
            option = options[i];
            value = option.value,
            text = option.firstChild.nodeValue;
            previous = seen[value];
            if (typeof previous === "string" && text === previous) {
                selectNode.removeChild(option);
            } else {
                seen[value] = text;
            }
        }
    }
    
    removeDuplicateOptions("Fruits");
    

    On jsfiddle

    0 讨论(0)
  • 提交回复
    热议问题