I am working on a website and I've ran into a problem.
I have a 12x24 table using nth-child()
and I want to use jQuery to check which nth-child()
is being clicked.
Currently I have tried:
$('table.masteries tr.p0 td').click(function() {
if($(this) == $('table.masteries tr.p0 td:nth-child(1)')) {
console.log('true')
}
});
But I get no response in the console.
The table is layed out as follows:
<table class="masteries">
<tr class="p0">
<td></td>
...
</tr>
<tr class="p4">
<td></td>
...
</tr>
<tr class="p8">
<td></td>
...
</tr>
<tr class="p12">
<td></td>
...
</tr>
<tr class="p16">
<td></td>
...
</tr>
<tr class="p20">
<td></td>
...
</tr>
<table>
So I wondered if it wasn't possible to check if $(this)
can work in if-statements or not.
If it isn't, is there another way of checking for certain nth-child()
with jQuery/Javascript if-statements?
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
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 .
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
:nth-child() Back You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() . For example, li:nth-child(3) will select the list item with an index value 3; that is, it will select the third list item.
You can use jQuery's .index()
method to find what index the current element has, or use jQuery's .is()
method to perform a check using CSS selectors.
$('table.masteries tr.p0 td').click(function() {
var $this = $(this);
// You don't need to use these together, both should work independently
if ($this.index() === 0 || $this.is(':nth-child(1)')) {
console.log('true')
}
});
I suggest using $(this).index()
to get the index of the element in relation to it's siblings.
.index() Documentation
For example to check if it's the first one...
$('table.masteries tr.p0 td').click(function() {
if($(this).index() == 0) {
console.log('true')
}
});
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