:nth-of-type(n) does not work as expected

2019-08-10 21:56发布

问题:

When using :nth-of-type(n) to make a selection it does not return the expected response.

I'm wanting to select the second <td> element with className b.

Why when using selector .b:nth-of-type(2) yield no result?

  <div id="foot">
    <table id="nav">
      <tbody>
        <tr valign="top">
          <td class="b"><b>Previous</b></td>
          <td><b>1</b></td>
          <td><a href="#">2</a></td>
          <td><a href="#">3</a></td>
          <td><a href="#">4</a></td>
          <td><a href="#">5</a></td>
          <td><a href="#">6</a></td>
          <td><a href="#">7</a></td>
          <td><a href="#">8</a></td>
          <td><a href="#">9</a></td>
          <td><a href="#">10</a></td>
          <td class="b"><a href="#">Next</a></td>
        </tr>
      </tbody>
    </table>
  </div>

Stipulations

  1. The number of <td> elements can change.
  2. pure JavaScript/CSS only.

Although .b:nth-last-child(1) would work,
this question is to understand why .b:nth-child(2) does not return the same.

Example Fiddle

回答1:

From W3C Specs

The :nth-of-type() pseudo-class represents an element that has an+b siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element.

So it looks like you can't use class name to select elements along with this pseudo class.

+:nth-of-type()



回答2:

as @Sourabh already said, nth-of-type isn't correct in this case, nth-child (or last-child in this case) is the correct way to go. I updated your fiddle. Your markup was inconsistent as well. In the first .b you have a <b> element, while in the second(last one), you had an <a> tag.