JavaScript remove() doesn't work in IE

前端 未结 5 2024

I have the following code in JavaScript:

all_el_ul = document.getElementsByClassName(\'element_list\')[0];
div_list = all_el_ul.getElementsByTagName(\"div\")         


        
5条回答
  •  没有蜡笔的小新
    2020-12-05 04:50

    The native childNode.remove() is a new experimental method that is not is supported in Internet Explorer, only in Edge

    Compatibility table from MDN

    You could use the more widely supported Node.removeChild instead

    var all_el_ul = document.getElementsByClassName('element_list')[0];
    var div_list  = all_el_ul.getElementsByTagName("div");
    
    for (i = 0; i < div_list.length; i += 1) {         
       div_list[i].parentNode.removeChild(div_list[i]);             
    }
    

    or use the polyfill from MDN to add support for all browsers

    (function (arr) {
      arr.forEach(function (item) {
        if (item.hasOwnProperty('remove')) {
          return;
        }
        Object.defineProperty(item, 'remove', {
          configurable: true,
          enumerable: true,
          writable: true,
          value: function remove() {
            this.parentNode.removeChild(this);
          }
        });
      });
    })([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
    

    There is also a remove() method in jQuery, that does work cross-browser, but that would require adding the jQuery library.

    $('.element_list').first().find('div').remove();
    

    As a sidenote getElementsByClassName only works from IE9 and up, using querySelector would add IE8 support as well

    var all_el_ul = document.querySelector('.element_list');
    

提交回复
热议问题