Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery nth-child selector

Got a small confusing issue with jQuery and selecting/styling a column in a table.

The following code works:

   $(function() {
      $("table").delegate('th.selcol','click', function(e) {
         var iCol = $(this).parent().children().index(this)+1;
         $("table tr td:nth-child(10)").each(function () {
            $(this).toggleClass("colhighlight");
         });
      });
   });

But this code, changing the nth-child(10) to nth-child(iCol) produces an error "uncaught exception: Syntax error, unrecognized expression: :nth-child"

   $(function() {
      $("table").delegate('th.selcol','click', function(e) {
         var iCol = $(this).parent().children().index(this)+1;
         $("table tr td:nth-child(iCol)").each(function () {
            $(this).toggleClass("colhighlight");
         });
      });
   });

Any help would be greatly appreciated.

like image 543
chrisk Avatar asked May 27 '11 10:05

chrisk


People also ask

What is nth child in jQuery?

Definition and Usage. The :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.

What's the difference between the nth of type () and Nth child () selector?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .

How do you use the nth child in querySelector?

To get the nth-child of an element using the querySelector method, pass the :nth-child() pseudo-class as a parameter to the method, e.g. document. querySelector('#parent :nth-child(1)') . The nth-child pseudo-class returns the element that matches the specified position.

How can I get second child in jQuery?

Using jQuery :nth-child Selector You have put the position of an element as its argument which is 2 as you want to select the second li element. If you want to get the exact element, you have to specify the index value of the item. A list element starts with an index 0.


2 Answers

     $("table tr td:nth-child(" + iCol + ")").each(function () {
        $(this).toggleClass("colhighlight");
     });

nth-child expects an integer, not a string, so you can use concatenation to solve your problem.

like image 121
Berry Langerak Avatar answered Sep 20 '22 13:09

Berry Langerak


Try this:

"table tr td:nth-child("+iCol+")"
like image 43
Blazes Avatar answered Sep 19 '22 13:09

Blazes