Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?












78















Is there a way to select every nth child that matches (or does not match) an arbitrary selector? For example, I want to select every odd table row, but within a subset of the rows:



table.myClass tr.row:nth-child(odd) {
...
}


<table class="myClass">
<tr>
<td>Row
<tr class="row"> <!-- I want this -->
<td>Row
<tr class="row">
<td>Row
<tr class="row"> <!-- And this -->
<td>Row
</table>


But :nth-child() just seems to count all the tr elements regardless of whether or not they're of the "row" class, so I end up with the one even "row" element instead of the two I'm looking for. The same thing happens with :nth-of-type().



Can someone explain why?










share|improve this question





























    78















    Is there a way to select every nth child that matches (or does not match) an arbitrary selector? For example, I want to select every odd table row, but within a subset of the rows:



    table.myClass tr.row:nth-child(odd) {
    ...
    }


    <table class="myClass">
    <tr>
    <td>Row
    <tr class="row"> <!-- I want this -->
    <td>Row
    <tr class="row">
    <td>Row
    <tr class="row"> <!-- And this -->
    <td>Row
    </table>


    But :nth-child() just seems to count all the tr elements regardless of whether or not they're of the "row" class, so I end up with the one even "row" element instead of the two I'm looking for. The same thing happens with :nth-of-type().



    Can someone explain why?










    share|improve this question



























      78












      78








      78


      20






      Is there a way to select every nth child that matches (or does not match) an arbitrary selector? For example, I want to select every odd table row, but within a subset of the rows:



      table.myClass tr.row:nth-child(odd) {
      ...
      }


      <table class="myClass">
      <tr>
      <td>Row
      <tr class="row"> <!-- I want this -->
      <td>Row
      <tr class="row">
      <td>Row
      <tr class="row"> <!-- And this -->
      <td>Row
      </table>


      But :nth-child() just seems to count all the tr elements regardless of whether or not they're of the "row" class, so I end up with the one even "row" element instead of the two I'm looking for. The same thing happens with :nth-of-type().



      Can someone explain why?










      share|improve this question
















      Is there a way to select every nth child that matches (or does not match) an arbitrary selector? For example, I want to select every odd table row, but within a subset of the rows:



      table.myClass tr.row:nth-child(odd) {
      ...
      }


      <table class="myClass">
      <tr>
      <td>Row
      <tr class="row"> <!-- I want this -->
      <td>Row
      <tr class="row">
      <td>Row
      <tr class="row"> <!-- And this -->
      <td>Row
      </table>


      But :nth-child() just seems to count all the tr elements regardless of whether or not they're of the "row" class, so I end up with the one even "row" element instead of the two I'm looking for. The same thing happens with :nth-of-type().



      Can someone explain why?







      css css3 css-selectors






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 17 '16 at 16:45









      BoltClock

      518k12811531194




      518k12811531194










      asked Apr 4 '11 at 23:50









      atanamiratanamir

      3,04021717




      3,04021717
























          4 Answers
          4






          active

          oldest

          votes


















          103














          This is a very common problem that arises due to a misunderstanding of how :nth-child() and :nth-of-type() work. Unfortunately, there is currently no selector-based solution as yet because Selectors does not provide a way to match the nth child that matches an arbitrary selector based on a pattern such as odd-numbered, even-numbered or any an+b where a != 1 and b != 0. This extends beyond just class selectors, to attribute selectors, negations, and more complex combinations of simple selectors.



          The :nth-child() pseudo-class counts elements among all of their siblings under the same parent. It does not count only the siblings that match the rest of the selector. Similarly, the :nth-of-type() pseudo-class counts siblings sharing the same element type, which refers to the tag name in HTML, and not the rest of the selector.



          This also means that if all the children of the same parent are of the same element type, for example in the case of a table body whose only children are tr elements or a list element whose only children are li elements, then :nth-child() and :nth-of-type() will behave identically, i.e. for every value of an+b, :nth-child(an+b) and :nth-of-type(an+b) will match the same set of elements.



          In fact, all simple selectors in a given compound selector, including pseudo-classes such as :nth-child() and :not(), work independently of one another, rather than looking at the subset of elements that are matched by the rest of the selector.



          This also implies that there is no notion of order among simple selectors within each individual compound selector1, which means for example the following two selectors are equivalent:



          table.myClass tr.row:nth-child(odd)
          table.myClass tr:nth-child(odd).row


          Translated to English, they both mean:




          Select any tr element that matches all of the following independent conditions:




          • it is an odd-numbered child of its parent;

          • it has the class "row"; and

          • it is a descendant of a table element that has the class "myClass".




          (you'll notice my use of an unordered list here, just to drive the point home)



          Because there is currently no pure CSS solution, you'll have to use a script to filter elements and apply styles or extra class names accordingly. For example, the following is a common workaround using jQuery (assuming there is only one row group populated with tr elements within the table):



          $('table.myClass').each(function() {
          // Note that, confusingly, jQuery's filter pseudos are 0-indexed
          // while CSS :nth-child() is 1-indexed
          $('tr.row:even').addClass('odd');
          });


          With the corresponding CSS:



          table.myClass tr.row.odd {
          ...
          }


          If you're using automated testing tools such as Selenium or processing HTML with tools like lxml, many of these tools allow XPath as an alternative:



          //table[contains(concat(' ', @class, ' '), ' myClass ')]//tr[contains(concat(' ', @class, ' '), ' row ')][position() mod 2)=1]


          Other solutions using different technologies are left as an exercise to the reader; this is just a brief, contrived example for illustration.





          For what it's worth, there is a proposal for an extension to the :nth-child() notation to be added to Selectors level 4 for the specific purpose of selecting every nth child matching a given selector.2



          The selector by which to filter matches is provided as an argument to :nth-child(), again due to how selectors operate independently of one another in a sequence as dictated by the existing selector syntax. So in your case, it would look like this:



          table.myClass tr:nth-child(odd of .row)


          (An astute reader will note right away that this ought to be :nth-child(odd of tr.row) instead, since the simple selectors tr and :nth-child() operate independently of one another as well. This is one of the problems with functional pseudo-classes that accept selectors, a can of worms I'd rather not open in the middle of this answer. Instead I'm going to go with the assumption that most sites will not have any other elements than tr elements as siblings of one another in a table body, which would make either option functionally equivalent.)



          Of course, being a brand new proposal in a brand new specification, this probably won't see implementation until a few years down the road. In the meantime, you'll have to stick with using a script, as above.





          1If you specify a type or universal selector, it must come first. This does not change how selectors fundamentally work, however; it's nothing more than a syntactic quirk.



          2This was originally proposed as :nth-match(), however because it still counts an element relative only to its siblings, and not to every other element that matches the given selector, it has since as of 2014 been repurposed as an extension to the existing :nth-child() instead.






          share|improve this answer





















          • 3





            "(you'll notice my use of an unordered list here, just to drive the point home)" I wish more people were that deliberate about their use of ordered vs unordered bullets. Thank you for your answer.

            – The Red Pea
            Aug 28 '16 at 0:40






          • 1





            @The Red Pea: One of my biggest HTML pet peeves: "In order from highest/lowest to lowest/highest:" followed by an unordered list. I mean come on, seriously?

            – BoltClock
            Aug 28 '16 at 7:15



















          6














          Not really..



          quote from the docs




          The :nth-child pseudo-class matches an
          element that has an+b-1 siblings
          before it in the document tree
          , for a
          given positive or zero value for n,
          and has a parent element.




          It is a selector of its own and does not combine with classes. In your rule it just has to satisfy both selector at the same time, so it will show the :nth-child(even) table rows if they also happen to have the .row class.






          share|improve this answer

































            0














            nth-of-type works according to the index of same type of the element but nth-child works only according to index no matter what type of siblings elements are.



            For example



            <div class="one">...</div>
            <div class="two">...</div>
            <div class="three">...</div>
            <div class="four">...</div>
            <div class="five">...</div>
            <div class="rest">...</div>
            <div class="rest">...</div>
            <div class="rest">...</div>
            <div class="rest">...</div>
            <div class="rest">...</div>


            Suppose in above html we want to hide all the elements having rest class.



            In this case nth-child and nth-of-type will work exactly same as all the element are of same type that is <div> so css should be



            .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
            display:none;
            }


            OR



            .rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
            display:none;
            }


            Now you must be wondering what is the difference between nth-child and nth-of-type so this is the difference



            Suppose the html is



            <div class="one">...</div>
            <div class="two">...</div>
            <div class="three">...</div>
            <div class="four">...</div>
            <div class="five">...</div>
            <p class="rest">...</p>
            <p class="rest">...</p>
            <p class="rest">...</p>
            <p class="rest">...</p>
            <p class="rest">...</p>


            In the above html the type of .rest element is different from others .rest are paragraphs and others are div so in this case if you use nth-child you have to write like this



            .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
            display:none;
            }


            but if you use nth-of-type css can be this



            .rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
            display:none;
            }



            As type of .rest element is <p> so here nth-of-type is detecting the type of .rest and then he applied css on the 1st, 2nd, 3rd, 4th, 5th element of <p>.







            share|improve this answer
























            • How useful is that for <tr> tags?

              – Alexis Wilke
              Oct 12 '16 at 21:07



















            0














            You may be able to do that with xpath. something like //tr[contains(@class, 'row') and position() mod 2 = 0] might work. There are other SO questions expanding on the details how to match classes more precisely.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5545649%2fcan-i-combine-nth-child-or-nth-of-type-with-an-arbitrary-selector%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              103














              This is a very common problem that arises due to a misunderstanding of how :nth-child() and :nth-of-type() work. Unfortunately, there is currently no selector-based solution as yet because Selectors does not provide a way to match the nth child that matches an arbitrary selector based on a pattern such as odd-numbered, even-numbered or any an+b where a != 1 and b != 0. This extends beyond just class selectors, to attribute selectors, negations, and more complex combinations of simple selectors.



              The :nth-child() pseudo-class counts elements among all of their siblings under the same parent. It does not count only the siblings that match the rest of the selector. Similarly, the :nth-of-type() pseudo-class counts siblings sharing the same element type, which refers to the tag name in HTML, and not the rest of the selector.



              This also means that if all the children of the same parent are of the same element type, for example in the case of a table body whose only children are tr elements or a list element whose only children are li elements, then :nth-child() and :nth-of-type() will behave identically, i.e. for every value of an+b, :nth-child(an+b) and :nth-of-type(an+b) will match the same set of elements.



              In fact, all simple selectors in a given compound selector, including pseudo-classes such as :nth-child() and :not(), work independently of one another, rather than looking at the subset of elements that are matched by the rest of the selector.



              This also implies that there is no notion of order among simple selectors within each individual compound selector1, which means for example the following two selectors are equivalent:



              table.myClass tr.row:nth-child(odd)
              table.myClass tr:nth-child(odd).row


              Translated to English, they both mean:




              Select any tr element that matches all of the following independent conditions:




              • it is an odd-numbered child of its parent;

              • it has the class "row"; and

              • it is a descendant of a table element that has the class "myClass".




              (you'll notice my use of an unordered list here, just to drive the point home)



              Because there is currently no pure CSS solution, you'll have to use a script to filter elements and apply styles or extra class names accordingly. For example, the following is a common workaround using jQuery (assuming there is only one row group populated with tr elements within the table):



              $('table.myClass').each(function() {
              // Note that, confusingly, jQuery's filter pseudos are 0-indexed
              // while CSS :nth-child() is 1-indexed
              $('tr.row:even').addClass('odd');
              });


              With the corresponding CSS:



              table.myClass tr.row.odd {
              ...
              }


              If you're using automated testing tools such as Selenium or processing HTML with tools like lxml, many of these tools allow XPath as an alternative:



              //table[contains(concat(' ', @class, ' '), ' myClass ')]//tr[contains(concat(' ', @class, ' '), ' row ')][position() mod 2)=1]


              Other solutions using different technologies are left as an exercise to the reader; this is just a brief, contrived example for illustration.





              For what it's worth, there is a proposal for an extension to the :nth-child() notation to be added to Selectors level 4 for the specific purpose of selecting every nth child matching a given selector.2



              The selector by which to filter matches is provided as an argument to :nth-child(), again due to how selectors operate independently of one another in a sequence as dictated by the existing selector syntax. So in your case, it would look like this:



              table.myClass tr:nth-child(odd of .row)


              (An astute reader will note right away that this ought to be :nth-child(odd of tr.row) instead, since the simple selectors tr and :nth-child() operate independently of one another as well. This is one of the problems with functional pseudo-classes that accept selectors, a can of worms I'd rather not open in the middle of this answer. Instead I'm going to go with the assumption that most sites will not have any other elements than tr elements as siblings of one another in a table body, which would make either option functionally equivalent.)



              Of course, being a brand new proposal in a brand new specification, this probably won't see implementation until a few years down the road. In the meantime, you'll have to stick with using a script, as above.





              1If you specify a type or universal selector, it must come first. This does not change how selectors fundamentally work, however; it's nothing more than a syntactic quirk.



              2This was originally proposed as :nth-match(), however because it still counts an element relative only to its siblings, and not to every other element that matches the given selector, it has since as of 2014 been repurposed as an extension to the existing :nth-child() instead.






              share|improve this answer





















              • 3





                "(you'll notice my use of an unordered list here, just to drive the point home)" I wish more people were that deliberate about their use of ordered vs unordered bullets. Thank you for your answer.

                – The Red Pea
                Aug 28 '16 at 0:40






              • 1





                @The Red Pea: One of my biggest HTML pet peeves: "In order from highest/lowest to lowest/highest:" followed by an unordered list. I mean come on, seriously?

                – BoltClock
                Aug 28 '16 at 7:15
















              103














              This is a very common problem that arises due to a misunderstanding of how :nth-child() and :nth-of-type() work. Unfortunately, there is currently no selector-based solution as yet because Selectors does not provide a way to match the nth child that matches an arbitrary selector based on a pattern such as odd-numbered, even-numbered or any an+b where a != 1 and b != 0. This extends beyond just class selectors, to attribute selectors, negations, and more complex combinations of simple selectors.



              The :nth-child() pseudo-class counts elements among all of their siblings under the same parent. It does not count only the siblings that match the rest of the selector. Similarly, the :nth-of-type() pseudo-class counts siblings sharing the same element type, which refers to the tag name in HTML, and not the rest of the selector.



              This also means that if all the children of the same parent are of the same element type, for example in the case of a table body whose only children are tr elements or a list element whose only children are li elements, then :nth-child() and :nth-of-type() will behave identically, i.e. for every value of an+b, :nth-child(an+b) and :nth-of-type(an+b) will match the same set of elements.



              In fact, all simple selectors in a given compound selector, including pseudo-classes such as :nth-child() and :not(), work independently of one another, rather than looking at the subset of elements that are matched by the rest of the selector.



              This also implies that there is no notion of order among simple selectors within each individual compound selector1, which means for example the following two selectors are equivalent:



              table.myClass tr.row:nth-child(odd)
              table.myClass tr:nth-child(odd).row


              Translated to English, they both mean:




              Select any tr element that matches all of the following independent conditions:




              • it is an odd-numbered child of its parent;

              • it has the class "row"; and

              • it is a descendant of a table element that has the class "myClass".




              (you'll notice my use of an unordered list here, just to drive the point home)



              Because there is currently no pure CSS solution, you'll have to use a script to filter elements and apply styles or extra class names accordingly. For example, the following is a common workaround using jQuery (assuming there is only one row group populated with tr elements within the table):



              $('table.myClass').each(function() {
              // Note that, confusingly, jQuery's filter pseudos are 0-indexed
              // while CSS :nth-child() is 1-indexed
              $('tr.row:even').addClass('odd');
              });


              With the corresponding CSS:



              table.myClass tr.row.odd {
              ...
              }


              If you're using automated testing tools such as Selenium or processing HTML with tools like lxml, many of these tools allow XPath as an alternative:



              //table[contains(concat(' ', @class, ' '), ' myClass ')]//tr[contains(concat(' ', @class, ' '), ' row ')][position() mod 2)=1]


              Other solutions using different technologies are left as an exercise to the reader; this is just a brief, contrived example for illustration.





              For what it's worth, there is a proposal for an extension to the :nth-child() notation to be added to Selectors level 4 for the specific purpose of selecting every nth child matching a given selector.2



              The selector by which to filter matches is provided as an argument to :nth-child(), again due to how selectors operate independently of one another in a sequence as dictated by the existing selector syntax. So in your case, it would look like this:



              table.myClass tr:nth-child(odd of .row)


              (An astute reader will note right away that this ought to be :nth-child(odd of tr.row) instead, since the simple selectors tr and :nth-child() operate independently of one another as well. This is one of the problems with functional pseudo-classes that accept selectors, a can of worms I'd rather not open in the middle of this answer. Instead I'm going to go with the assumption that most sites will not have any other elements than tr elements as siblings of one another in a table body, which would make either option functionally equivalent.)



              Of course, being a brand new proposal in a brand new specification, this probably won't see implementation until a few years down the road. In the meantime, you'll have to stick with using a script, as above.





              1If you specify a type or universal selector, it must come first. This does not change how selectors fundamentally work, however; it's nothing more than a syntactic quirk.



              2This was originally proposed as :nth-match(), however because it still counts an element relative only to its siblings, and not to every other element that matches the given selector, it has since as of 2014 been repurposed as an extension to the existing :nth-child() instead.






              share|improve this answer





















              • 3





                "(you'll notice my use of an unordered list here, just to drive the point home)" I wish more people were that deliberate about their use of ordered vs unordered bullets. Thank you for your answer.

                – The Red Pea
                Aug 28 '16 at 0:40






              • 1





                @The Red Pea: One of my biggest HTML pet peeves: "In order from highest/lowest to lowest/highest:" followed by an unordered list. I mean come on, seriously?

                – BoltClock
                Aug 28 '16 at 7:15














              103












              103








              103







              This is a very common problem that arises due to a misunderstanding of how :nth-child() and :nth-of-type() work. Unfortunately, there is currently no selector-based solution as yet because Selectors does not provide a way to match the nth child that matches an arbitrary selector based on a pattern such as odd-numbered, even-numbered or any an+b where a != 1 and b != 0. This extends beyond just class selectors, to attribute selectors, negations, and more complex combinations of simple selectors.



              The :nth-child() pseudo-class counts elements among all of their siblings under the same parent. It does not count only the siblings that match the rest of the selector. Similarly, the :nth-of-type() pseudo-class counts siblings sharing the same element type, which refers to the tag name in HTML, and not the rest of the selector.



              This also means that if all the children of the same parent are of the same element type, for example in the case of a table body whose only children are tr elements or a list element whose only children are li elements, then :nth-child() and :nth-of-type() will behave identically, i.e. for every value of an+b, :nth-child(an+b) and :nth-of-type(an+b) will match the same set of elements.



              In fact, all simple selectors in a given compound selector, including pseudo-classes such as :nth-child() and :not(), work independently of one another, rather than looking at the subset of elements that are matched by the rest of the selector.



              This also implies that there is no notion of order among simple selectors within each individual compound selector1, which means for example the following two selectors are equivalent:



              table.myClass tr.row:nth-child(odd)
              table.myClass tr:nth-child(odd).row


              Translated to English, they both mean:




              Select any tr element that matches all of the following independent conditions:




              • it is an odd-numbered child of its parent;

              • it has the class "row"; and

              • it is a descendant of a table element that has the class "myClass".




              (you'll notice my use of an unordered list here, just to drive the point home)



              Because there is currently no pure CSS solution, you'll have to use a script to filter elements and apply styles or extra class names accordingly. For example, the following is a common workaround using jQuery (assuming there is only one row group populated with tr elements within the table):



              $('table.myClass').each(function() {
              // Note that, confusingly, jQuery's filter pseudos are 0-indexed
              // while CSS :nth-child() is 1-indexed
              $('tr.row:even').addClass('odd');
              });


              With the corresponding CSS:



              table.myClass tr.row.odd {
              ...
              }


              If you're using automated testing tools such as Selenium or processing HTML with tools like lxml, many of these tools allow XPath as an alternative:



              //table[contains(concat(' ', @class, ' '), ' myClass ')]//tr[contains(concat(' ', @class, ' '), ' row ')][position() mod 2)=1]


              Other solutions using different technologies are left as an exercise to the reader; this is just a brief, contrived example for illustration.





              For what it's worth, there is a proposal for an extension to the :nth-child() notation to be added to Selectors level 4 for the specific purpose of selecting every nth child matching a given selector.2



              The selector by which to filter matches is provided as an argument to :nth-child(), again due to how selectors operate independently of one another in a sequence as dictated by the existing selector syntax. So in your case, it would look like this:



              table.myClass tr:nth-child(odd of .row)


              (An astute reader will note right away that this ought to be :nth-child(odd of tr.row) instead, since the simple selectors tr and :nth-child() operate independently of one another as well. This is one of the problems with functional pseudo-classes that accept selectors, a can of worms I'd rather not open in the middle of this answer. Instead I'm going to go with the assumption that most sites will not have any other elements than tr elements as siblings of one another in a table body, which would make either option functionally equivalent.)



              Of course, being a brand new proposal in a brand new specification, this probably won't see implementation until a few years down the road. In the meantime, you'll have to stick with using a script, as above.





              1If you specify a type or universal selector, it must come first. This does not change how selectors fundamentally work, however; it's nothing more than a syntactic quirk.



              2This was originally proposed as :nth-match(), however because it still counts an element relative only to its siblings, and not to every other element that matches the given selector, it has since as of 2014 been repurposed as an extension to the existing :nth-child() instead.






              share|improve this answer















              This is a very common problem that arises due to a misunderstanding of how :nth-child() and :nth-of-type() work. Unfortunately, there is currently no selector-based solution as yet because Selectors does not provide a way to match the nth child that matches an arbitrary selector based on a pattern such as odd-numbered, even-numbered or any an+b where a != 1 and b != 0. This extends beyond just class selectors, to attribute selectors, negations, and more complex combinations of simple selectors.



              The :nth-child() pseudo-class counts elements among all of their siblings under the same parent. It does not count only the siblings that match the rest of the selector. Similarly, the :nth-of-type() pseudo-class counts siblings sharing the same element type, which refers to the tag name in HTML, and not the rest of the selector.



              This also means that if all the children of the same parent are of the same element type, for example in the case of a table body whose only children are tr elements or a list element whose only children are li elements, then :nth-child() and :nth-of-type() will behave identically, i.e. for every value of an+b, :nth-child(an+b) and :nth-of-type(an+b) will match the same set of elements.



              In fact, all simple selectors in a given compound selector, including pseudo-classes such as :nth-child() and :not(), work independently of one another, rather than looking at the subset of elements that are matched by the rest of the selector.



              This also implies that there is no notion of order among simple selectors within each individual compound selector1, which means for example the following two selectors are equivalent:



              table.myClass tr.row:nth-child(odd)
              table.myClass tr:nth-child(odd).row


              Translated to English, they both mean:




              Select any tr element that matches all of the following independent conditions:




              • it is an odd-numbered child of its parent;

              • it has the class "row"; and

              • it is a descendant of a table element that has the class "myClass".




              (you'll notice my use of an unordered list here, just to drive the point home)



              Because there is currently no pure CSS solution, you'll have to use a script to filter elements and apply styles or extra class names accordingly. For example, the following is a common workaround using jQuery (assuming there is only one row group populated with tr elements within the table):



              $('table.myClass').each(function() {
              // Note that, confusingly, jQuery's filter pseudos are 0-indexed
              // while CSS :nth-child() is 1-indexed
              $('tr.row:even').addClass('odd');
              });


              With the corresponding CSS:



              table.myClass tr.row.odd {
              ...
              }


              If you're using automated testing tools such as Selenium or processing HTML with tools like lxml, many of these tools allow XPath as an alternative:



              //table[contains(concat(' ', @class, ' '), ' myClass ')]//tr[contains(concat(' ', @class, ' '), ' row ')][position() mod 2)=1]


              Other solutions using different technologies are left as an exercise to the reader; this is just a brief, contrived example for illustration.





              For what it's worth, there is a proposal for an extension to the :nth-child() notation to be added to Selectors level 4 for the specific purpose of selecting every nth child matching a given selector.2



              The selector by which to filter matches is provided as an argument to :nth-child(), again due to how selectors operate independently of one another in a sequence as dictated by the existing selector syntax. So in your case, it would look like this:



              table.myClass tr:nth-child(odd of .row)


              (An astute reader will note right away that this ought to be :nth-child(odd of tr.row) instead, since the simple selectors tr and :nth-child() operate independently of one another as well. This is one of the problems with functional pseudo-classes that accept selectors, a can of worms I'd rather not open in the middle of this answer. Instead I'm going to go with the assumption that most sites will not have any other elements than tr elements as siblings of one another in a table body, which would make either option functionally equivalent.)



              Of course, being a brand new proposal in a brand new specification, this probably won't see implementation until a few years down the road. In the meantime, you'll have to stick with using a script, as above.





              1If you specify a type or universal selector, it must come first. This does not change how selectors fundamentally work, however; it's nothing more than a syntactic quirk.



              2This was originally proposed as :nth-match(), however because it still counts an element relative only to its siblings, and not to every other element that matches the given selector, it has since as of 2014 been repurposed as an extension to the existing :nth-child() instead.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 9 '16 at 4:06

























              answered Apr 5 '11 at 1:50









              BoltClockBoltClock

              518k12811531194




              518k12811531194








              • 3





                "(you'll notice my use of an unordered list here, just to drive the point home)" I wish more people were that deliberate about their use of ordered vs unordered bullets. Thank you for your answer.

                – The Red Pea
                Aug 28 '16 at 0:40






              • 1





                @The Red Pea: One of my biggest HTML pet peeves: "In order from highest/lowest to lowest/highest:" followed by an unordered list. I mean come on, seriously?

                – BoltClock
                Aug 28 '16 at 7:15














              • 3





                "(you'll notice my use of an unordered list here, just to drive the point home)" I wish more people were that deliberate about their use of ordered vs unordered bullets. Thank you for your answer.

                – The Red Pea
                Aug 28 '16 at 0:40






              • 1





                @The Red Pea: One of my biggest HTML pet peeves: "In order from highest/lowest to lowest/highest:" followed by an unordered list. I mean come on, seriously?

                – BoltClock
                Aug 28 '16 at 7:15








              3




              3





              "(you'll notice my use of an unordered list here, just to drive the point home)" I wish more people were that deliberate about their use of ordered vs unordered bullets. Thank you for your answer.

              – The Red Pea
              Aug 28 '16 at 0:40





              "(you'll notice my use of an unordered list here, just to drive the point home)" I wish more people were that deliberate about their use of ordered vs unordered bullets. Thank you for your answer.

              – The Red Pea
              Aug 28 '16 at 0:40




              1




              1





              @The Red Pea: One of my biggest HTML pet peeves: "In order from highest/lowest to lowest/highest:" followed by an unordered list. I mean come on, seriously?

              – BoltClock
              Aug 28 '16 at 7:15





              @The Red Pea: One of my biggest HTML pet peeves: "In order from highest/lowest to lowest/highest:" followed by an unordered list. I mean come on, seriously?

              – BoltClock
              Aug 28 '16 at 7:15













              6














              Not really..



              quote from the docs




              The :nth-child pseudo-class matches an
              element that has an+b-1 siblings
              before it in the document tree
              , for a
              given positive or zero value for n,
              and has a parent element.




              It is a selector of its own and does not combine with classes. In your rule it just has to satisfy both selector at the same time, so it will show the :nth-child(even) table rows if they also happen to have the .row class.






              share|improve this answer






























                6














                Not really..



                quote from the docs




                The :nth-child pseudo-class matches an
                element that has an+b-1 siblings
                before it in the document tree
                , for a
                given positive or zero value for n,
                and has a parent element.




                It is a selector of its own and does not combine with classes. In your rule it just has to satisfy both selector at the same time, so it will show the :nth-child(even) table rows if they also happen to have the .row class.






                share|improve this answer




























                  6












                  6








                  6







                  Not really..



                  quote from the docs




                  The :nth-child pseudo-class matches an
                  element that has an+b-1 siblings
                  before it in the document tree
                  , for a
                  given positive or zero value for n,
                  and has a parent element.




                  It is a selector of its own and does not combine with classes. In your rule it just has to satisfy both selector at the same time, so it will show the :nth-child(even) table rows if they also happen to have the .row class.






                  share|improve this answer















                  Not really..



                  quote from the docs




                  The :nth-child pseudo-class matches an
                  element that has an+b-1 siblings
                  before it in the document tree
                  , for a
                  given positive or zero value for n,
                  and has a parent element.




                  It is a selector of its own and does not combine with classes. In your rule it just has to satisfy both selector at the same time, so it will show the :nth-child(even) table rows if they also happen to have the .row class.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 20 '16 at 9:24

























                  answered Apr 5 '11 at 0:10









                  Gabriele PetrioliGabriele Petrioli

                  149k23198254




                  149k23198254























                      0














                      nth-of-type works according to the index of same type of the element but nth-child works only according to index no matter what type of siblings elements are.



                      For example



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>


                      Suppose in above html we want to hide all the elements having rest class.



                      In this case nth-child and nth-of-type will work exactly same as all the element are of same type that is <div> so css should be



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      OR



                      .rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
                      display:none;
                      }


                      Now you must be wondering what is the difference between nth-child and nth-of-type so this is the difference



                      Suppose the html is



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>


                      In the above html the type of .rest element is different from others .rest are paragraphs and others are div so in this case if you use nth-child you have to write like this



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      but if you use nth-of-type css can be this



                      .rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
                      display:none;
                      }



                      As type of .rest element is <p> so here nth-of-type is detecting the type of .rest and then he applied css on the 1st, 2nd, 3rd, 4th, 5th element of <p>.







                      share|improve this answer
























                      • How useful is that for <tr> tags?

                        – Alexis Wilke
                        Oct 12 '16 at 21:07
















                      0














                      nth-of-type works according to the index of same type of the element but nth-child works only according to index no matter what type of siblings elements are.



                      For example



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>


                      Suppose in above html we want to hide all the elements having rest class.



                      In this case nth-child and nth-of-type will work exactly same as all the element are of same type that is <div> so css should be



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      OR



                      .rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
                      display:none;
                      }


                      Now you must be wondering what is the difference between nth-child and nth-of-type so this is the difference



                      Suppose the html is



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>


                      In the above html the type of .rest element is different from others .rest are paragraphs and others are div so in this case if you use nth-child you have to write like this



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      but if you use nth-of-type css can be this



                      .rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
                      display:none;
                      }



                      As type of .rest element is <p> so here nth-of-type is detecting the type of .rest and then he applied css on the 1st, 2nd, 3rd, 4th, 5th element of <p>.







                      share|improve this answer
























                      • How useful is that for <tr> tags?

                        – Alexis Wilke
                        Oct 12 '16 at 21:07














                      0












                      0








                      0







                      nth-of-type works according to the index of same type of the element but nth-child works only according to index no matter what type of siblings elements are.



                      For example



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>


                      Suppose in above html we want to hide all the elements having rest class.



                      In this case nth-child and nth-of-type will work exactly same as all the element are of same type that is <div> so css should be



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      OR



                      .rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
                      display:none;
                      }


                      Now you must be wondering what is the difference between nth-child and nth-of-type so this is the difference



                      Suppose the html is



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>


                      In the above html the type of .rest element is different from others .rest are paragraphs and others are div so in this case if you use nth-child you have to write like this



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      but if you use nth-of-type css can be this



                      .rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
                      display:none;
                      }



                      As type of .rest element is <p> so here nth-of-type is detecting the type of .rest and then he applied css on the 1st, 2nd, 3rd, 4th, 5th element of <p>.







                      share|improve this answer













                      nth-of-type works according to the index of same type of the element but nth-child works only according to index no matter what type of siblings elements are.



                      For example



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>
                      <div class="rest">...</div>


                      Suppose in above html we want to hide all the elements having rest class.



                      In this case nth-child and nth-of-type will work exactly same as all the element are of same type that is <div> so css should be



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      OR



                      .rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
                      display:none;
                      }


                      Now you must be wondering what is the difference between nth-child and nth-of-type so this is the difference



                      Suppose the html is



                      <div class="one">...</div>
                      <div class="two">...</div>
                      <div class="three">...</div>
                      <div class="four">...</div>
                      <div class="five">...</div>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>
                      <p class="rest">...</p>


                      In the above html the type of .rest element is different from others .rest are paragraphs and others are div so in this case if you use nth-child you have to write like this



                      .rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
                      display:none;
                      }


                      but if you use nth-of-type css can be this



                      .rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
                      display:none;
                      }



                      As type of .rest element is <p> so here nth-of-type is detecting the type of .rest and then he applied css on the 1st, 2nd, 3rd, 4th, 5th element of <p>.








                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 4 '16 at 10:41









                      Gaurav AggarwalGaurav Aggarwal

                      7,27131848




                      7,27131848













                      • How useful is that for <tr> tags?

                        – Alexis Wilke
                        Oct 12 '16 at 21:07



















                      • How useful is that for <tr> tags?

                        – Alexis Wilke
                        Oct 12 '16 at 21:07

















                      How useful is that for <tr> tags?

                      – Alexis Wilke
                      Oct 12 '16 at 21:07





                      How useful is that for <tr> tags?

                      – Alexis Wilke
                      Oct 12 '16 at 21:07











                      0














                      You may be able to do that with xpath. something like //tr[contains(@class, 'row') and position() mod 2 = 0] might work. There are other SO questions expanding on the details how to match classes more precisely.






                      share|improve this answer




























                        0














                        You may be able to do that with xpath. something like //tr[contains(@class, 'row') and position() mod 2 = 0] might work. There are other SO questions expanding on the details how to match classes more precisely.






                        share|improve this answer


























                          0












                          0








                          0







                          You may be able to do that with xpath. something like //tr[contains(@class, 'row') and position() mod 2 = 0] might work. There are other SO questions expanding on the details how to match classes more precisely.






                          share|improve this answer













                          You may be able to do that with xpath. something like //tr[contains(@class, 'row') and position() mod 2 = 0] might work. There are other SO questions expanding on the details how to match classes more precisely.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 4 '16 at 23:27









                          the8472the8472

                          26.2k23278




                          26.2k23278






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5545649%2fcan-i-combine-nth-child-or-nth-of-type-with-an-arbitrary-selector%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Monofisismo

                              Angular Downloading a file using contenturl with Basic Authentication

                              Olmecas