nth-child javascript code example

Example 1: javascript get element nth child

//you can use the css nth-child property like this:
var second-child = document.querySeletorAll('[your element name]:nth-child(2)');

Example 2: nth-child() css

/* Selects the second <li> element in a list */
li:nth-child(2) { 
  color: lime;
}

/* Selects every fourth element
   among any group of siblings */
:nth-child(4n) {
  color: lime;
}

Example 3: css nth child

/* Select the first list item */
li:nth-child(1) { }

/* Select the 5th list item */
li:nth-child(5) { }

/* Select every other list item starting with first */
li:nth-child(odd) { }

/* Select every 3rd list item starting with first */
li:nth-child(3n) { }

/* Select every 3rd list item starting with 2nd */
li:nth-child(3n - 1) { }

/* Select every 3rd child item, as long as it has class "el" */
.el:nth-child(3) { }

Example 4: how to get the nth child of dom js

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

Tags:

Css Example