2

I have a <select> element on my page which has onchange propery set:

<select id="MySelect" onchange="return myOnChange(this);">Whatever</select>

The event handler goes like this:

function myOnChange(select) {
   var parentNode = select.parentNode;
   //whatever
}

Once the page has loaded the user changes the selection inside the dropdown and the event handler is invoked and parentNode is bound to something (whatever it is, it's not undefined and that's enough).

However if I add a document.ready():

$(document).ready(function () {
  var select = $('#MySelect');
  var parentNode = select.parentNode;
  //whatever
});

or window.load():

$(window).load(function () {
  var select = $('#MySelect');
  var parentNode = select.parentNode;
  //whatever
});

then once either of them is invoked then parentNode is undefined.

Why is this? How do I have my handler invoked once the page has loaded such that parentNode is not undefined?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • jQuery functions return a list of nodes, not a DOM node. – Oriol Mar 25 '16 at 14:25
  • @Oriol I'd say that this question is only a duplicate of that one for people who already know there're two kinds of objects. I had no idea of that - to me it was "working here but not there" and the answer was "there're two kinds of objects, here's how you access the right one". – sharptooth Mar 28 '16 at 06:36

2 Answers2

2

because here is no parentNode in a jQuery object.

var parentNode = select.parent()

or

var parentNode = select[0].parentNode;
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

You are accessing a node object's property over a jquery object,

var select = $('#MySelect');
var parentNode = select.parent();

You have to use jquery's .parent() function.

In your onchange event handler you are receiving the this as its parameter. Basically the this over their would represent the element which invokes the event. And that would be the node object. So over that you could access the property parentNode. But not over a jquery object.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130