jquery parent element versus parentNode

jquery parent element versus parentNode

pwc1011pwc1011 Posts: 62Questions: 0Answers: 0
edited January 2010 in General
It seems as though the jQuery selector returns a different object than the parentNode function in javascript. For example, if I get the row selected using

[code]
var row = $(this).parent("tr");
[/code]

I get the row, however, when I pass it to fnGetPostion(row), the object does not contain the nodeName property of "TR", so the row is not found and null is returned.

The alternative is to use

[code]
var row = $(this).parentNode.parentNode;
[/code]

However, this does not appear to work from within a jQuery function.

Anyone have any suggestions?

Thanks

Replies

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin
    edited January 2010
    Hi pwc1011,

    I think either of these will work:

    [code]
    var row = $(this).parent("tr")[0];
    // or
    var row = $(this)[0].parentNode.parentNode;
    // or
    var row = this.parentNode.parentNode;
    [/code]
    Remember the jQuery object returns an array of nodes, but arrays in Javascript are actually objects, and jQuery takes advantages of this by adding methods and properties to the object as well as the array elements :-)

    Worth noting that the last option in the list should be the fastest, the first likely to be the slowest (although the different will be tiny). However the first is the most flexible since it will cope with a deeper DOM tree...

    Regards,
    Allan
  • pwc1011pwc1011 Posts: 62Questions: 0Answers: 0
    Thank you very much! I did get a similar response on the jQuery site. They also talked about $(this.parentNode.parentNode). I had already tried this, and it didn't work.

    I'll post my final solution. Thanks again!

    Patrick
  • supersoniquesupersonique Posts: 6Questions: 0Answers: 0
    And the final solution is ?
  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin
    Which of the three options I suggested have you tried? They should all work (assuming the DOM struct is the same - i.e. two children down).

    Allan
  • witsiwitwitsiwit Posts: 4Questions: 0Answers: 0
    [code]var row = this.parentNode.parentNode;[/code]

    this is working i think, because when i try to display the row, alert displays [object],
    but how will u use it?
This discussion has been closed.