Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this.parentElement?

pg.myfunc = function(){
    var i = 1, j = 2;
    this.selected = 1;
    xx.newObject = this.parentElement;

...

What is xx.newObject = this.parentElement; doing?

like image 515
Asim Zaidi Avatar asked May 24 '10 18:05

Asim Zaidi


People also ask

What is the use of parentElement in Javascript?

The parent element is read only property which returns the parent element of the selected element. The element object represents an HTML element, like P, DIV, etc. Return Value: The parentElement property returns an element object representing parent element if present or else it will return null.

How do you get parentElement?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it. In HTML, the document is itself the parent node of html element.

What is the difference between parentNode and parentElement?

parentNode gives the parent, while . parentElement gives undefined.


2 Answers

It's the same as this.parentNode: it gives you the node that contains this as a childNode. this will be pg, presumably an Element of some kind; this.parentNode will be the Element that contains it, or the document object if pg is the root element.

parentElement is a non-standard IE extension. Since IE also supports the standard property parentNode, parentElement should never be used.

Alternatively, maybe it's just an arbitrary object with a property called parentElement, in which case it could be anything at all. There's no real way to tell from that code, but it would be unusual to be setting arbitrary properties like myfunc on an Element node.

like image 168
bobince Avatar answered Sep 21 '22 12:09

bobince


It saves a reference to the parent element of this. So for example:

<div id="parent">
  <span id="child">
  </span>
</div>

In this case, if this corresponds to the child span, parentElement would correspond to the parent div.

That said, you should always use parentNode instead of parentElement, as parentElement is proprietary and (I believe) only works with IE. According to MSDN:

There is no public standard that applies to this property.

like image 22
Justin Ethier Avatar answered Sep 20 '22 12:09

Justin Ethier