Que- What is Traversing the DOM?
Ans- Everything in an HTML DOM is a node; the entire document, every HTML element, text inside HTML elements, attributes, and comments everything is a node; & navigating between these nodes is known as DOM Traversing.
DOM Relationships
The terms parent, child, and sibling are used to describe relationships.
• In a node tree, the top node is called the root
• Every node has exactly one parent, except the root
• A node can have a number of children
• Siblings are nodes with the same parent
Traversal / Navigating between Nodes
Syntax:
element.parentElement.nodeName
Methods:
• parentNode & parentElement
• childNodes & children
• firstChild & firstElement
• lastChild & lastElement
• nextSibling & nextElementSibling
• previousSibling & previousElementSibling
1. parentNode & parentElement
These properties return the parent of the specified element. The difference is parentElement returns null if a node does not have any parent.
2. childNodes & children
These properties return child nodes. The difference is that childNodes
returns all child nodes including text, spaces, and comments.
Where children
only return child elements (not text or comments)
3. firstChild & firstElementChild
firstChild is based on childNodes it returns the first node of the element according to childNodes indexing.
firstElementChild is based on children it returns the first node of the element according to children indexing.
4. lastChild & lastElementChild
lastChild is based on childNodes it returns the last node of the element according to childNodes indexing.
lastElementChild is based on children it returns the last node of the element according to children indexing.
5. nextSibling & nextElementSibling
These properties return next (after) siblings of an Element. nextSibling follows the childNodes indexing rule. nextElementSibling follows the children indexing rule.
6. previousSibling & previousElementSibling
These properties return previous (before) siblings of an Element. previousSibling follows the childNodes indexing rule. previousElementSibling follows the children indexing rule.
If you liked this article, make sure to
- Follow me ✅
- Like this post 👍
Thanks so much for getting to the end of it 🙏😍
Alfaiz ⚡@imAlfaiz
• Aspiring Frontend Developer - Student - Web Dev 🎨
• DM for Collaboration💌