-2

I have the following CSS code:

article ul ul :nth-child(2) {
    border:1px solid black;
}

Which selects every second element in the dom tree, regardless of the depth in tree. (but it has to be inside an ul, which has to be inside of an ul, which has to be inside of an article).

But why does this not select every second item in this example?

article ul ul :nth-child(2) {
  border: 1px solid black;
}
<article>
  <ul>
    <li>this not</li>
    <li>this not</li>
    <ul>
      <li>this not</li>
      <li>this</li>
      <p>
        <li>this not</li>
        <li>why not this?</li>
      </p>
    </ul>
  </ul>
</article>

But when I change the p element to a div it works. Can somebody explain this?

Huangism
  • 16,278
  • 7
  • 48
  • 74
Dirk
  • 23
  • 5
  • 2
    You should correct your html to valid html then it will work. `ul` cannot be inside of another `ul` as a child. It should be list item then `ul` inside of the list item. Your paragraph tag should be inside of list item as well and not as a child of `ul` – Huangism Jul 13 '18 at 13:29
  • inspect the element and you see your fault – Temani Afif Jul 13 '18 at 13:35
  • See [this](https://stackoverflow.com/a/5681796/7377521) – Rohit Sharma Jul 13 '18 at 13:36

2 Answers2

1

Your markup is invalid. a ul may only have li elements as its immediate descendants. Furthermore, li is an invalid child of p. Paragraph tags may only contain phrasing content, which does not include li. I suggest you inspect the following snippet to see how your browser is altering to try to correct for your markup mistakes. At least for chrome, it ends up splitting the paragraph tag in two and placing the nested li elements on the same level as the others.

article ul ul :nth-child(2) {
  border:1px solid black;
}
<article>
  <ul>
    <li>this not</li>
    <li>this not</li>
    <ul>
      <li>this not</li>
      <li>this</li>
      <p>
        <li>this not</li>
        <li>why not this?</li>
            </p>
    </ul>
  </ul>
</article>
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

As @Huangism already mentioned, your HTML is invalid.

From MDN page about ul:

Permitted content:
zero or more <li> elements, which in turn often contain nested <ol> or <ul> elements.

Here is an example of how your dom would need to be structured for it to work:

article ul ul :nth-child(2) {
  border: 1px solid black;
}
<article>
  <ul>
    <li>this not</li>
    <li>this not</li>
    <li>
      <ul>
        <li>this not</li>
        <li>this</li>
        <li>
          <ul>
            <li>this not</li>
            <li>why not this?</li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</article>
Maharkus
  • 2,841
  • 21
  • 35