nwcat
nwcat

Reputation: 99

What is the relationship between Document and Element? Why does a parent element also have getElementsByTagName method?

I've been really troubled in the relationship between Document and Element since I found that a ul element also can use getElementsByTagName method to get its descendants.

I can understand that the document object, as an instance of Document, has those methods that is inherited from Document. But I can't understand why an instance of Element also have those methods.

Where are those methods from? What is the relationship between Document and Element?

Upvotes: 4

Views: 126

Answers (1)

Jordan Running
Jordan Running

Reputation: 106077

Strictly speaking, Document.getElementsByTagName and Element.getElementsByTagName are different methods. But it makes sense for both Document and Element to have such a method: A document has "child" elements, and an element does, too.

To answer your broader question, Document and Element both inherit from Node (as do DocumentFragment and a few other interfaces). Node defines a number of properties and methods common to Document and Element, such as nodeType, childNodes, and appendChild(). As MDN notes, "These interfaces may return null in particular cases where the methods and properties are not relevant," so e.g. document.parentNode returns null. But as it turns out, your example getElementsByTagName isn't defined by Node—it's defined separately by Document and Element.

For understanding the DOM, MDN (where all of the above links lead) is your best friend. It'll tell you not only what each property and method is for, but also what interface it's defined in.

Upvotes: 3

Related Questions