1

I have the following jquery code:

 jQuery(function ($) {
    $(document).on('click', '.del', function () {
        var self = $(this);
        parent = self.parents('.transportRow');
        parent.remove();
    });
});

When i click a link with the class "del" inside a div with the class "transportRow" the div should be removed.

This is working fine in Webkit and Firefox, but not in IE

I get an error that tells me that the object does not support the property or method "remove".

When i inspect it in the debugger, parent seems to be the window, not the div element.

Does anybody know how to get this script running in IE?

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
wertzui
  • 5,148
  • 3
  • 31
  • 51
  • 1
    Try changing `self` to some other name, in JavaScript, `self` is `window` – Ranganadh Paramkusam Mar 10 '14 at 13:14
  • 2
    @ranganadh That's not always the case. `self` can be set to anything. Typically, you'll see `var self = this;`. In this case `self` is based on the current context of `this`. It could be the window, but it does not have to be. See [this](http://stackoverflow.com/questions/3309516/when-to-use-self-in-javascript#answer-3309557) answer for reference... – War10ck Mar 10 '14 at 13:16
  • 1
    what version please ... – Arno 2501 Mar 10 '14 at 13:19
  • Having you tried logging `self` and `parent`? Try `console.log(self);` and `console.log(parent);` to see what the values contain. – War10ck Mar 10 '14 at 13:19
  • 1
    Strangely, this seems to fix it: `var parent = self.parents('.transportRow');` (tested IE10) EDIT: looks like global `parent` variable refers to Window on IE10 (other ???) – A. Wolff Mar 10 '14 at 13:20
  • @War10ck In IE11, self works like a normal variable, but I've no idea about lower versions of IE – Ranganadh Paramkusam Mar 10 '14 at 13:23
  • @ranganadh Should work like a normal variable in all version of IE. I've seen the `var self = this;` syntax a lot in MV* frameworks like Knockoutjs. It's very common and works across all browsers. – War10ck Mar 10 '14 at 13:24

1 Answers1

5

When you use parent without var you refer to the global variable parent a.k.a. the parent property on the global (window) object.

In IE the window.parent property is readonly (in reality it is the property attribute [[Writable]] of the property that is set to false or not set at all).

Changing the row:

parent = self.parents('.transportRow');

to

var parent = self.parents('.transportRow');

should do the trick. Or change names.

Crockford talks about this issue and recommends using that instead of self. This advice is also applicable on parent I say.

anddoutoi
  • 9,973
  • 4
  • 29
  • 28
  • 1
    **+1** On mentioning `that`, Even though comments above that explained the legitimacy of using self; I see no reason to put yourself & code in that situation where it still '*could*' become a problem through JavaScript's quirky scoping (Although it's entirely preference) – MackieeE Mar 10 '14 at 13:41