Skip to content Skip to sidebar Skip to footer

How To Select A Specific Html Element From Identical Nested Divs

I need to select a specific HTML element, which are identical, also contain inside several identical div's, I tried with nth-child() but it did not work. (Each child shares same pr

Solution 1:

Here's how you could do it.

.disc_PF
{
  width: 50px;
  height: 50px;
}

/* First .disc, all .disc_PF */.disc:nth-of-type(1) > .disc_PF
{
  background: red;
}
/* Second .disc, first .disc_PF */.disc:nth-of-type(2) > .disc_PF:first-child
{
  background: green;
}
/* Second .disc, .disc_PF that is the second child element */.disc:nth-of-type(2) > .disc_PF:nth-child(2)
{
  background: yellow;
}
/* Second .disc, last .disc_PF */.disc:nth-of-type(2) > .disc_PF:last-child
{
  background: blue;
}
<divclass="disc"><divclass="disc_PF"></div></div><divclass="disc"><divclass="disc_PF"></div><divclass="disc_PF"></div><divclass="disc_PF"></div></div>

Solution 2:

Nth child starts counting from the element's parent, so if you have two elements from different parents where each is the second child of its own parent, you will be selecting both of them.

Try this:

.disc:nth-child(2) .disc_PF:nth-child(1) {}

Solution 3:

.disc_PF
{
 width:100px;
 height:100px;
 float: left;
}

/* 1st .disc, all .disc_PF */.disc:nth-of-type(1) > .disc_PF
{
  border:1px solid #ccc;
  background:#ccc;
}
/* 2nd .disc, 1st .disc_PF */.disc:nth-of-type(2) > .disc_PF:first-child
{
  border:3px double #111;
}
/* 2nd .disc, 2nd .disc_PF  */.disc:nth-of-type(2) > .disc_PF:nth-child(2)
{
  border:1px solid #0f0;
}
/* 2nd .disc, 3rd .disc_PF */.disc:nth-of-type(2) > .disc_PF:last-child
{
  border:1px solid #00f;
}
<divclass="disc"><divclass="disc_PF">
  1st disc_PF
  </div></div><divclass="disc"><divclass="disc_PF">
  2nd disc_PF
  </div><divclass="disc_PF">
  3rd disc_PF
  </div><divclass="disc_PF">
  4th disc_PF
  </div></div>

Solution 4:

:nth-of-type() and :nth-child only work on element names, not classnames. In other words,

.classname:nth-child(2) 

doesn't work, but

div:nth-child(2)

does. Similarly, something like .my-class:first-child() will not select the first element with .my-classunless it's a first child.

Given your code example, the only options you have are either to add ids to the elements, or select any <div> based on it's position (first child, etc).

Post a Comment for "How To Select A Specific Html Element From Identical Nested Divs"