0

Would anyone happen to know why appending a text node to a div, in the manner shown below, seems to associate something other than the original div to the text node's parent?

More importantly, is it possible in jQuery to somehow get back the original div from the text node (after the appending has happened)?

I am using jquery 1.11.0, testing on firefox 31.0 and eclipse Kepler. Any help would be greatly appreciated.

var
  div = $("<div>"),
  text = $(document.createTextNode("Hello there")); // Will need to detach later
                                                    // to append elsewhere.

$(document.body).append(div);

// I thought this would make div the parent of text.
div.append(text);

// Apparently I was mistaken as this alerts "some other parent".
if(text.parent() === div) alert("expected parent"); else alert("some other parent");
efru
  • 31
  • 3

1 Answers1

2

You can not compare jQuery objects, they are plain objects, and no two objects are the same, hence this fails

$('#element') === $('#element'); // fail

and so would this

text.parent() === div

you can however compare native DOM nodes

text.parent().get(0) === div.get(0)

so

if ( text.parent().get(0) === div.get(0) ) ...
adeneo
  • 312,895
  • 29
  • 395
  • 388