Dom Traversal
With the HTML DOM, we can easily navigate the node tree using node relationships.
When a html page gets loaded. A node tree/dom tree gets created within ram. The different methods of DOM traversal are :
1)parentNode
2)parentElement
3)childNodes
4)children
5)firstChild
6)firstElementChild
7)lastChild
8)lastElementChild
9)previousSibling
10)previousElementSibling
11)nextSibling
12)nextElementSibling
1)parentNode vs parentElement
parentNode : Let us see an example
Output :
Scenario 2 :
Let us take the reference of h1 tag
Output :
childNodes vs children
1)childNodes : It returns an array. The child node is a read only property that returns a live NodeList of child nodes of the given element. The first child child has index of 0 .
Child nodes will contain :
1)whitespace inside the element. Text : Text again considered as node
2)tab sign
3)enter
4)return
5)comment
Output :
Now if we want to get , what is the data of #text node
Now apply the comment:
Out :
Child nodes of body :
Output
Note : During the creation of the node tree. The js engine puts the <script>..</script> inside the body tag
See above ex
Finding the style as node inside the head tag
7 child nodes :
Put the style outside the head
Output :
Now , find the child node inside text
Text node does not contain any further child :
Find the child nodes for the paragraph tag :
Output :
Note : span does have one text node. And text node do not have any further node
Children for the element : It only considers the html element. It does not consider the space,enter,backspace, comment , return
Children of head tag :
Output :
Children of h1 tag :
Output
Output :
Because the .children is returning the array of HTML collection. So to find the length
Let us loop the nodes:
Change the css
Change the attributes
1)loop
Output :
Apply css
Output :
firstChild vs firstElementChild
firstChild will tell about the first node
firstChild calculates the space,comment,backspace,enter,return
Output :
Output :
Output :
Apply the css to specific node
Output :
Another way to get the reference of p tag
Note :
a)previousElementSibling : That checks only html elment
b)previousSibling : It checks the #text node
lastChild vs lastElementChild
Output :
Output:
lastSibling vs lastElementSibling
Output :
How to work on dynamic element :
Up To now we are only traversing through the node tree. Now we are going to create new node and then we will append it acc to the requirement
1)Create the element node (html ka element)
Output :
Create text node : It is text node (word)
Output :
Comment node
Output :
Append the newly created element to dom element
1)
Output :
insertBefore :
Remove dom element
Before
After
Remove the child element
Output :
When we click on the element , it needs to be deleted
Output :