nodes in js
Hey, i hear "nodes" floating around when people talk about certain things in js. But what exactly are they and how do they differ from elements? There are some methods that are for nodes and some that aren't e.g.
parentElement
and parentNode
and it seems pretty confusing since they at first sight seem to be doing the same thing?
I'd appreciate any info, thanks in advance.15 Replies
This question is better suited to #discussions since it's not about specific code.
But in brief, everything in the DOM as far as JS is concerned is a node.
main
element? Yep, that's a node. The text of a p
element? That's a text node.
Just like in HTML all block-level elements are fancy div
s, in JS everything in the DOM is a fancy node.
https://developer.mozilla.org/en-US/docs/Web/API/Nodeoh okay my bad.
ah okay, so why does js have different functions and methods for elements and nodes if an element = a node to js, shouldn't it be one or the other?
Text nodes are not elements.
All elements are nodes, but not all nodes are elements
so the only nodes that aren't elements are text nodes?
and text nodes are elements that are supposed to contain text?
using your
main
example though. let's say i wanted to get the parent of a div, which would be a node, it's confusing on whether to use div.parentElement
or div.parentNode
.No, there are so many more nodes. For example,
attr
is a node. You get it using the Element.getAttribute()
method
HTML elements are Element
s. So if you want an HTML element like a div
, p
, strong
, etc you want to get the elementohh okay so the
parentElement
one is for elements (duh haha), but then when would you use parentNode since your example of an attr
has it's own way of getting that?No. There are also attribute nodes, comment nodes, and a few others, but text nodes are the ones used most in DOM manipulation.
ah okay i see, thanks
everything is a node, in the dom model used by xml/html
yeah that i defo understand, it's just the need for the different methods/functions between
element
and node
that confuses mebut not all nodes are html elements
if it exists, it's a node
what type of node? that doesn't matter: it is a node
you were given a short list of existing node types, but there are more
one that's not as common is a
cdata
node
https://developer.mozilla.org/en-US/docs/Web/API/CDATASection
also, this dom model isn't just for html, but for xml as wellah i'll take a look at that then. So as beck said, essentially if you want an element use
element
. But you could technically use node
but i guess it's not recommended right?no, those are different things
an element is a node
but a node isn't an element
an html element node has a very specific api, different from an element and different from a node
an html element has, for example, a dataset
but an xml element doesn't have a dataset
a node also doesn't have a dataset
ahh okay i see, thanks