Difference between Node object and Element object?
Asked Answered
M

5

444

I am totally confused between Node object and Element object. document.getElementById() returns Element object while document.getElementsByClassName() returns NodeList object (Collection of Elements or Nodes?)

If a div is an Element Object then what about div Node object?

What is a Node Object?

Are document object, Element object and Text Object are also Node object?

As per David Flanagan's book 'The Document object, Its Element Objects and text objects are all Node objects'.

So How come an object can inherit properties/methods of Element object as well as Node object?

If yes, I guess Node Class and Element Class are related in prototypal tree of inheritance.

 <div id="test">
           <p class="para"> 123 </p>
           <p class="para"> abc </p>
 </div>
 <p id="id_para"> next </p>

document.documentElement.toString();    // [object HTMLHtmlElement]

var div = document.getElementById("test");
div.toString();                         // [object HTMLDivElement]                       

var p1 = document.getElementById("id_para");
p1.toString();                          // [object HTMLParagraphElement]

var p2 = document.getElementsByClassName("para");
p2.toString();                          //[object HTMLCollection]
Malacology answered 2/4, 2012 at 15:28 Comment(5)
There are 12 types of nodes, element being one of themLarrylars
aren't all these 12 types are Element Object also? like 1 = ELEMENT_NODE, 3 = TEXT_NODE, I think both are Element object also.Malacology
No they aren't. Element is only a single type of node.Larrylars
Is this still in used nowadays? I ask since seeing Mozilla's docs it says: var elements = document.getElementsByClassName(names); elements is a live HTMLCollection of found elements. So, apparently, getElementsByClassName does not return a NodeList anymore.Desiccant
The WHATWG: The nodes representing HTML elements in the DOM... (3.2.2). Some nitpicker could draw from it there is kind of a difference here. Nevertheless, it seems the spec uses this terms (DOM nodes representing HTML elements and just HTML elements) in an interchangeable way.Malapert
H
686

A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document or document.body, it could be an HTML tag specified in the HTML such as <input> or <p> or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node is any DOM object.

An element is one specific type of node as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).

The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document node has the html node as its child. The html node has its list of child nodes (the head node and the body node). The body node would have its list of child nodes (the top level elements in your HTML page) and so on.

So, a nodeList is simply an array-like list of nodes.

An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id or a class. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):

enter image description here

You can see an ELEMENT_NODE is one particular type of node where the nodeType property has a value of 1.

So document.getElementById("test") can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.

Since document.getElementsByClassName("para") can return more than one object, the designers chose to return a nodeList because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList, but they chose to use just one type of collection whether it had only elements in it or not.


EDIT: HTML5 defines an HTMLCollection which is a list of HTML Elements (not any node, only Elements). A number of properties or methods in HTML5 now return an HTMLCollection. While it is very similar in interface to a nodeList, a distinction is now made in that it only contains Elements, not any type of node.

The distinction between a nodeList and an HTMLCollection has little impact on how you use one (as far as I can tell), but the designers of HTML5 have now made that distinction.

For example, the element.children property returns a live HTMLCollection.

Horten answered 2/4, 2012 at 16:5 Comment(5)
So all elements are nodes, but not all nodes are elements... right? I was just pondering whether to describe things as nodes or elements in JavaScript functions when iterating through certain things.Burkhalter
I know I'm resurrecting a 7-year-old post, but I just wanted to say thank you for this excellent and thorough explanation! Made complete sense.Crucifer
Wow, thank you for this wonderful answer. Very brief, yet very thorough. And answered the questions and confusion I alway had in my head as to why we call this thing nodeList rather than elementList. Thank you!Dispatch
Very good answer. Just a small correction: "The document node would have its list of child nodes (the head node and the body node)." — The head and body nodes are not children of document. document has one child, which is html (document.documentElement). document.documentElement / html is the parent of head and body. :-)Aboveboard
@Aboveboard - Thx. I've updated the answer to reflect that it goes document > [html] > [head, body] and so on...Horten
S
102

Element inherits from Node, in the same way that Dog inherits from Animal.

An Element object "is-a" Node object, in the same way that a Dog object "is-a" Animal object.

Node is for implementing a tree structure, so its methods are for firstChild, lastChild, childNodes, etc. It is more of a class for a generic tree structure.

And then, some Node objects are also Element objects. Element inherits from Node. Element objects actually represents the objects as specified in the HTML file by the tags such as <div id="content"></div>. The Element class define properties and methods such as attributes, id, innerHTML, clientWidth, blur(), and focus().

Some Node objects are text nodes and they are not Element objects. Each Node object has a nodeType property that indicates what type of node it is, for HTML documents:

1: Element node
3: Text node
8: Comment node
9: the top level node, which is document

We can see some examples in the console:

> document instanceof Node
  true

> document instanceof Element
  false

> document.firstChild
  <html>...</html>

> document.firstChild instanceof Node
  true

> document.firstChild instanceof Element
  true

> document.firstChild.firstChild.nextElementSibling
  <body>...</body>

> document.firstChild.firstChild.nextElementSibling === document.body
  true

> document.firstChild.firstChild.nextSibling
  #text

> document.firstChild.firstChild.nextSibling instanceof Node
  true

> document.firstChild.firstChild.nextSibling instanceof Element
  false

> Element.prototype.__proto__ === Node.prototype
  true

The last line above shows that Element inherits from Node. (that line won't work in IE due to __proto__. Will need to use Chrome, Firefox, or Safari).

By the way, the document object is the top of the node tree, and document is a Document object, and Document inherits from Node as well:

> Document.prototype.__proto__ === Node.prototype
  true

Here are some docs for the Node and Element classes:
https://developer.mozilla.org/en-US/docs/DOM/Node
https://developer.mozilla.org/en-US/docs/DOM/Element

Slier answered 15/4, 2013 at 12:2 Comment(3)
What about <span data-a="1" >123</span> ? this span is an element which has it's own node. but does the attribute also has it's own node ?Riker
the only point I want to clarify is that Node is an interface not a class. from which a number of DOM API object types inherit. It allows those types to be treated similarly; for example, inheriting the same set of methods, or being tested in the same way. I found this in mozilla link that you refer to. thanks for precious answerGawky
What's good about you explanation is to use a simple ordinary thing in an analogy, name it dog, animal. Reader grabs it right away. Kudo!Schnitzler
F
13

Best source of information for all of your DOM woes

https://www.w3.org/TR/dom/#nodes

Objects implementing the Document, DocumentFragment, DocumentType, Element, Text, ProcessingInstruction, or Comment interface (simply called nodes) participate in a tree.

https://www.w3.org/TR/dom/#element

Element nodes are simply known as elements.

Fortyfour answered 2/4, 2012 at 15:34 Comment(0)
E
8

Node : http://www.w3schools.com/js/js_htmldom_nodes.asp

The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.

Element : http://www.w3schools.com/js/js_htmldom_elements.asp

The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.

duplicate :

Ergonomics answered 2/4, 2012 at 15:33 Comment(0)
B
6

Node is used to represent tags in general. Divided to 3 types:

Attribute Note: is node which inside its has attributes. Exp: <p id=”123”></p>

Text Node: is node which between the opening and closing its have contian text content. Exp: <p>Hello</p>

Element Node : is node which inside its has other tags. Exp: <p><b></b></p>

Each node may be types simultaneously, not necessarily only of a single type.

Element is simply a element node.

Backbend answered 7/3, 2016 at 10:51 Comment(2)
Apart from the last sentence, nothing in this answer is correct. 1 . A node tree represents "any markup-based resource", a node is a part of it but doesn't have to represent a tag because tags can be omitted. 2. An attribute noDe has nothing "inside" of it, it represents an attribute. 3. A text node represents text. Text doesn't have to be associated with tags but with a node of type TEXT_NODE(3).Idden
4. An element node doesn't have to contain anything or it can just contain a comment and/or some text. 5. Each node is of one type and one type only. node.nodeType returns (in general) a number between 1 and 12. Please improve your answer. For references dom.spec.whatwg.org/#node-trees, dom.spec.whatwg.org/#nodesIdden

© 2022 - 2024 — McMap. All rights reserved.