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.
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.
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 .
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.
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.
$("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.
Try this:
"table tr td:nth-child("+iCol+")"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With