traversing in js parent child sibling concept

 you can access child nodes i.e div or query using childnode concept or children concept

 childnode includes all text and new line as its children while children concept doesn't include extra lines and spaces as its children

 study by assuming a tree structure

 index.html

             <!DOCTYPE html>
<html>
<head>
<title> understanding dom</title>
</head>
<body>
<div class="container">
 <div class="abc">first div
  <ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  </ul>
 </div>
 <div class="abc">second div</div>
 <div class="abc">third div</div>
 <div class="abc">fourth div</div>
 </div>
</body>
<script type="text/javascript" src="javascript.js"></script>
</html>

js

    console.log('hello')
let element=document.querySelector('.container')
let nodes=element.childNodes
let nodes_that_dont_include_space=element.children
console.log(nodes)
console.log(nodes_that_dont_include_space)
let first_node=element.children[0]
console.log(first_node)
let second_node=element.children[1]
console.log(second_node)

 

   if you want to access 1st li of 1st div

   let parent=document.querySelector(".container")
let firstchild=parent.children[0]
let super_child=firstchild.children
console.log(super_child[0].children[0])


if you want to access fourth div

    let parent=document.querySelector(".container")
let firstchild=parent.children[3]
console.log(firstchild) 


 if you want to access first and last child explicetely

   let parent=document.querySelector(".container")
let firstchild=parent.firstElementChild
console.log(firstchild)
let lastchild=parent.lastElementChild
console.log(lastchild)


if you want to access sibling 

 let parent=document.querySelector(".container")
let firstchild=parent.firstElementChild
console.log(firstchild)
let sibling=firstchild.nextElementSibling
console.log(sibling)


access multiple siblings

     let parent=document.querySelector(".container")
let firstchild=parent.firstElementChild
console.log(firstchild)
let sibling=firstchild.nextElementSibling
let sibling2=firstchild.nextElementSibling.nextElementSibling
console.log(sibling)
console.log(sibling2)


Comments