javascript get element nth child 1

javascript get element nth child

 //method one 
  var c = document.getElementById("myDIV").childNodes;
  c[1].style.backgroundColor = "yellow";//first child
  c[2].style.backgroundColor = "red";//second child
  c[-1].style.backgroundColor = "green";//last child
  c[-2].style.backgroundColor = "blue";//secound last child
//method two
 let nth-child = document.querySeletorAll('myDiv:nth-child(n)');//gives nth child 

Here is what the above code is Doing:
1. The first line of code is getting the element with the id of myDIV.
2. The second line of code is getting the child nodes of the element with the id of myDIV.
3. The third line of code is changing the background color of the first child node to yellow.
4. The fourth line of code is changing the background color of the second child node to red.
5. The fifth line of code is changing the background color of the last child node to green.
6. The sixth line of code is changing the background color of the second to last child node to blue.
7. The seventh line of code is getting the nth child of the element with the id of myDIV.

Similar Posts