Transversing the DOM in JavaScript

Basically what you can do here is by selecting the element or nodes you can select its parent, sibling or children.

Nodes are a collection of nodelist and Element Nodes are HTML collection

First, let’s talk about nodes it’s a little bit confusing when you use nodes to select element because it will not only show it will show you the nodes.

Suppose you have ul list and you want to select its first element in node list if you select the first child then it will show you #text.

Because it is also considered as nodes the question is from where this #text is coming from?.

When you create li list they have space between them which are considered as nodes item that’s where it is coming from.

so if you want to select elements only then you could use element node which will only be going to select the elements.

let me show you some of the nodes of nodelist and element nodes and explain it to you one by one.

Childnodes;

childnodes; it will show you childs of nodes of the class which selected including the text as its child which I mentioned you before.

you can also index any of its node by using [ ] this bracket and putting the number of the node which you want to target

you can also see node name and node type by simply attaching it to the child node.

Let me show what is the value of which node type

Element = 1
Attribute(deprecated) = 2
Text node = 3
Comment = 8
Document itself = 9
Doctype = 10

You can target the first or last child of node list by simply adding it in from of child.

Same as if you want to target its next sibling then just add next sibling in front of the child.

Children;

Use children; to target only element nodes and I think it is an easy way you can also children’s of children by simply attaching with children node.

You can also index it like nodelist

Not only children you can also target parent and parent of the parent the same as children element you can also target its sibling by just adding nextElementsibling.

Not even that you can also target first child and last child in both nodelist and element node but in element node, you have to use firstElementchild and lastElementchild.

At last, you can also get the previous sibling both in nodelist and element node by just adding previous instead of next.

misterishaan
misterishaan
Articles: 47