惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security Affairs
L
Lohrmann on Cybersecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
WordPress大学
WordPress大学
小众软件
小众软件
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
F
Full Disclosure
S
Schneier on Security
L
LangChain Blog
MyScale Blog
MyScale Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
A
Arctic Wolf
Martin Fowler
Martin Fowler
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
Latest news
Latest news
F
Fortinet All Blogs
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
What's the Difference between DOM Node and Element?
Dmitri Pavlutin · 2021-01-06 · via Dmitri Pavlutin Blog

The Document Object Model (DOM) is an interface that treats HTML or XML document as a tree structure, where each node is an object of the document. DOM also provides a set of methods to query the tree, alter the structure, style.

DOM also uses the term element: which is quite similar to a node. So, what's the difference between a DOM node and an element? Let's find out!

1. DOM Node

The key to understanding the difference between a node and an element is to understand what a node is.

From a higher viewpoint, a DOM document consists of a hierarchy of nodes. Each node can have a parent and/or children.

Let's look at the following HTML document:


<!DOCTYPE html>

<html>

<head>

<title>My Page</title>

</head>

<body>

<!-- Page Body -->

<h2>My Page</h2>

<p id="content">Thank you for visiting my web page!</p>

</body>

</html>


The document contains the following hierarchy of nodes:

Hierarchy of DOM Nodes

<html> is a node in the document tree. It has 2 children: <head> and <body> nodes.

<body> is also a node having 3 children: a comment <!-- Page Body -->, heading <h2>, and paragraph <p>. The parent of the <body> node is <html> node.

The tags in the HTML document represent a node, what's interesting is that regular text is also a node. The paragraph node <p> has 1 child: the text node "Thank you for visiting my web page!".

1.2 Node Types

How can you distinguish these different types of nodes? The answer lays in the DOM Node interface, particularly in the Node.nodeType property.

Node.nodeType can have one of the following values that represents the type of the node:

  • Node.ELEMENT_NODE
  • Node.ATTRIBUTE_NODE
  • Node.TEXT_NODE
  • Node.CDATA_SECTION_NODE
  • Node.PROCESSING_INSTRUCTION_NODE
  • Node.COMMENT_NODE
  • Node.DOCUMENT_NODE
  • Node.DOCUMENT_TYPE_NODE
  • Node.DOCUMENT_FRAGMENT_NODE
  • Node.NOTATION_NODE

The constants meaningfully indicate the node type: for example Node.ELEMENT_NODE represents an element node, Node.TEXT_NODE represents a text node, Node.DOCUMENT_NODE the document node, and so on.

For example, let's select the paragraph node, and look at its nodeType property:


const paragraph = document.querySelector('p');

paragraph.nodeType === Node.ELEMENT_NODE; // => true


As expected paragraph.nodeType has the value Node.ELEMENT_NODE, indicating that the paragraph is an element.

The paragraph also contains a text node:


const paragraph = document.querySelector('p');

const firstChild = paragraph.childNodes[0];

firstChild.nodeType === Node.TEXT_NODE; // => true


There's a node type that represents the entire document tree of nodes — Node.DOCUMENT_NODE:


document.nodeType === Node.DOCUMENT_NODE; // => true


2. DOM Element

After getting a good grasp of what a DOM node is, now is the time to differentiate the DOM node and element.

If you get well the node term, then the answer is obvious: an element is a node of a specific type — element (Node.ELEMENT_NODE). Along with types like document, comment, text, etc.

In simple words, an element is a node that's written using a tag in the HTML document. <html>, <head>, <title>, <body>, <h2>, <p> are all elements because they are represented by tags.

The document type, the comment, the text nodes aren't elements because they are not written with tags:


<!DOCTYPE html>

<html>

<body>

<!-- Page Body -->

<p>

Thank you for visiting my web page!

</p>

</body>

</html>


Node is constructor of a node, and HTMLElement is a constructor of an element in JavaScript DOM. A paragraph, being a node and also an element, is an instance of both Node and HTMLElement:


const paragraph = document.querySelector('p');

paragraph instanceof Node; // => true

paragraph instanceof HTMLElement; // => true


Saying it simpler, an element is a subtype of a node the same way a cat is a subtype of an animal.

3. DOM properties: nodes and elements

Aside from differentiating nodes from elements, you need also to distinguish the DOM properties that contain specifically only nodes, or only elements.

The following properties of Node type evaluate to a node or a collection of nodes (NodeList):


node.parentNode; // Node or null

node.firstChild; // Node or null

node.lastChild; // Node or null

node.childNodes; // NodeList


However, the following properties are elements or collection of elements (HTMLCollection):


node.parentElement; // HTMLElement or null

node.children; // HTMLCollection


Since both node.childNodes and node.children return a list of children, why have both of these properties? Good question!

Consider the following paragraph element containing some text:


<p>

<b>Thank you</b> for visiting my web page!

</p>


Open the demo, then look at childNodes and children properties of the parapgraph node:


const paragraph = document.querySelector('p');

paragraph.childNodes; // NodeList: [HTMLElement, Text]

paragraph.children; // HTMLCollection: [HTMLElement]


paragraph.childNodes collection contains 2 nodes: the bold element <b>Thank you</b>, as well as the text node for visiting my web page!.

However, paragraph.children collection contains only 1 item: the bold element <b>Thank you</b>.

Because paragraph.children contains only elements, the text node wasn't included here because its type is text (Node.TEXT_NODE), and not an element (Node.ELEMENT_NODE).

Having both node.childNodes and node.children lets you choose the collection of children you'd like to access: all children nodes or only children being elements.

4. Summary

A DOM document is a hierarchical collection of nodes. Each node can have a parent and/or children.

Understanding the difference between a DOM node and an element is easy if you understand what a node is.

Nodes have types, the element type being one of them. The element is represented by a tag in the HTML document.

Quiz: What type of node never has a parent node?