Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

internet explorer - JavaScript remove() doesn't work in IE

I have the following code in JavaScript:

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

I know that this is the problem because I used alert('test'); to see where the code stops working. Everything is working in FF, Chrome, Opera and others but not in IE.

Could you please tell what is wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

IE doesn't support remove() native Javascript function but does support removeChild().

Browser compatibility for remove()

Desktop browser compatipility for remove() function

Mobile browser compatipility for remove() function

Solution n°1

Use remove() in pure Javascript you can declare it yourself with this following code :

// Create Element.remove() function if not exist
if (!('remove' in Element.prototype)) {
    Element.prototype.remove = function() {
        if (this.parentNode) {
            this.parentNode.removeChild(this);
        }
    };
}
// Call remove() according to your need
child.remove();

As you can see the function get the parent node of element and then remove this element from his parent with removeChild() native function.

Solution n°2

Use removeChild() in pure JavaScript on all browser including IE just call it insteed of remove().

element.removeChild(child);

More info on Mozilla Developer Network.

Solution n°3

Use jQuery through code.jquery.com CDN by using this following code :

<!-- Include jQuery -->
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<!-- Use remove() -->
<script>
child.remove();
</script>

The function is included in the jQuery library so you can call it after inclusion.

Happy coding ! :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...