JavaScript DOM Traversal Methods

JavaScript DOM Traversal Methods

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

6bed0f9d-46b1-4d48-8189-73e786455921.png

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.

api.typefully.png

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)

api.typefully.png

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. api.typefully.png

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. api.typefully.png

5. nextSibling & nextElementSibling

These properties return next (after) siblings of an Element. nextSibling follows the childNodes indexing rule. nextElementSibling follows the children indexing rule. api.typefully.png

6. previousSibling & previousElementSibling

These properties return previous (before) siblings of an Element. previousSibling follows the childNodes indexing rule. previousElementSibling follows the children indexing rule. api.typefully.png

If you liked this article, make sure to

  1. Follow me ✅
  2. Like this post 👍

Thanks so much for getting to the end of it 🙏😍

Alfaiz ⚡@imAlfaiz

• Aspiring Frontend Developer - Student - Web Dev 🎨

• DM for Collaboration💌