1

I'm learning JavaScript and I learned about the Node.parentNode property, which simply returns the parent of the current node. However, JavaScript also has another property called Node.parentElement, which seems like the same thing. I found out from this question that the difference is that parentElement will return null if the parent node is not an element.

I understand the difference between the two, but I can't imagine this ever being useful. Is it ever good practice to use parentElement instead of parentNode? If not, why does it exist?

Edit: The question I have linked is similar, but not the same as my question, because it is asking how the two properties behave differently. I know the difference, but I want to know what the actual purpose is of ever using parentElement, or if it's pretty much always bad practice and we should all agree to ignore parentElement. This specific question - the 'why' rather than the 'what' - was not answered here.

Alex Eberly
  • 15
  • 1
  • 5
  • Maybe when traversing an element's parents, and you don't want to get to the document node. – Bergi Apr 26 '19 at 18:02
  • Well parentElement doesn't prevent you from trying to return the value of the document node, it'll just return 'undefined.' Maybe there aren't any realistic use cases and the second part of my question could only be answered by the board that approved that decision. – Alex Eberly Apr 26 '19 at 18:26
  • DOM4 adds a lot of in-fill to improve the consistency between browsers. It's not backward compatible to remove methods and properties like `parentElement` from browsers that had it (in this case IE) but it's generally OK to add it to browsers that don't¹ . But from a usage perspective it's just a convenience, `parentNode` + test for node type will do just as well. (¹ Generally OK, bur for a weird case, see `document.all`) – Alohci Apr 27 '19 at 02:14
  • @Alohci If I wasn't marked as duplicate I would've accepted this answer – Alex Eberly Apr 29 '19 at 16:29

1 Answers1

0

It is, most of the time, pointless.
The difference is that the ParentNode is not always an Element, in which case ParentElement will return null.

James Conway
  • 339
  • 3
  • 20