Remove item from dropdown list on page load (no jquery)

前端 未结 7 1692

I have the following dropdown list:


                        
    
提交评论

  • 2020-12-18 12:12

    Since everyone else has proposed basically the same solution, here's a simpler solution if you have the benefit of only targeting modern browsers:

    var el = document.querySelector('select[name=DD1] option[value=D]');
    el.parentNode.removeChild(el);
    

    Or, for every browser:

    var el;
    if(typeof document.querySelector == 'function') {
      el = document.querySelector('select[name=DD1] option[value=D]');
    } else {
      for(var child in document.getElementById('DD1').childNodes) {
        if(child.textContent == 'D') {
          el = child;
          break;
        }
      }
    }
    
    el && el.parentNode.removeChild(el);
    
    0 讨论(0)
  • 2020-12-18 12:15

    I used window.addEventListener it won't work on down-level browsers that don't support it. I suggest creating your own addEvent method that abstracts the inconsistencies - if jQuery (or some other framework) is not allowed.

    window.addEventListener("load", function(){
       var list = document.getElementById('DD1'), el;
    
       for(var i in list.children){
           el = list.children[i];
           if(el.hasOwnProperty('value')) {
              if(el.value == 'D') {
                 el.style.display = 'none';
                 break;
              }
           }
       }
    }, false);
    

    http://jsfiddle.net/UV6nm/2/

    0 讨论(0)
  • 2020-12-18 12:15

    There's probably a little cleaner way to do this but I am rusty with javascript.

    var options = documentgetElementsByTagName("option");
    for(i=0; i<options.length; i++)
    {
       if(options[i].value == "D")
       {
         this.class += "displayNone";
       }
    }
    
    .displayNone{ display: none; }
    

    this is not tested so I don't know if it would work.

    0 讨论(0)
  • 2020-12-18 12:23
    var select=document.getElementById('DD1');
    
    for (i=0;i<select.length;  i++) {
       if (select.options[i].value=='D') {
         select.remove(i);
       }
    }
    
    0 讨论(0)
  • 2020-12-18 12:27

    Try looping over the options, checking the value, and if it matches, set it to null:

    function removeByValue(id, value) {
        var select = document.getElementById(id);
        for (var i=0, length = select.options.length; i< length; i++) {
    
            if (select.options[i] && select.options[i].value === value) {
                select.options[i] = null;
            }
        }
    }
    removeByValue('DD1', 'D');
    
    0 讨论(0)
  • 提交回复
    热议问题