JQuery this.remove () -vs.- $ ('# id'). remove () in Internet Explorer (IE 9+)

Why does this.remove() not work in IE9 +?

 <input type="button" value="Next1" id="nextButton1"> <br> <input type="button" value="Next2" id="nextButton2"> $('#nextButton1').on('click', function() { this.remove(); // works in all browsers but IE9+ }); $('#nextButton2').on('click', function() { $('#nextButton2').remove(); //works in all browsers }); 

JSFiddle Live

+6
source share
3 answers

This is because you are using the ChildNode.remove() method, which is not supported by all browsers.

 this ---> refers to a node. //WARNING: This is an experimental technology 

The jQuery .remove() method, however, is a cross browser, so to use it you must wrap this in $(...) as follows:

 $(this).remove(); 

Browser Compatibility ChildNode.remove ()

this.remove() supported by the following browsers on the desktop:

 - Chrome 23+ - Firefox 23+ - Opera 10+ - Safari 7+ 
+6
source

Wrap this in jQuery:

 $('#nextButton1').on('click', function() { $(this).remove(); }); 
+3
source

You asked why, so here is why:

In the context of the jQuery event handler, this refers to the reference to the DOM element that jQuery stores for the element for which you are currently handling events. Since the .remove() function you are going to use is a jQuery function and not a built-in DOM browser function, it does not work properly.

However, if you exchange the DOM link inside $() or jQuery() , so it becomes $(this) instead of this , the $ or jQuery function takes the DOM link as a parameter and returns a jQuery link, which can then contain jQuery member functions.

You can always pass your DOM links to jQuery and put jQuery links back

eg.

 var test = document.getElementById('test'); $(test).remove(); 

http://jsfiddle.net/2h45Y/

0
source

Source: https://habr.com/ru/post/970980/


All Articles