Search code examples
javascriptselectors-api

How can I combine an attribute and nth-of-type in querySelector?


I am trying to select a cell in a table by it's attribute (for which I could use querySelector("[data-name]"), but I want it to return the elements in the third column only. Is it possible to combine an attribute search with nth-of-type(2)?

I've tried using querySelector("[data-name]:nth-of-type(2)"] but that doesn't work.


Solution

  • for 3rd column try with nth-of-type(3)

    :nth-of-type() is a css selector and index of the first child will be 1

    http://www.w3schools.com/cssref/sel_nth-of-type.asp

    console.log(document.querySelector("table tr [data-name]:nth-of-type(3)"));
    <table>
      <tr>
        <td data-name="1">1</td>
           <td data-name="2">2</td>
            <td data-name="3">3</td>
        <tr>
          </table>