Luis de Haro
Luis de Haro

Reputation: 739

jQuery nth-child selector issue

I need to hide some columns of an html table using jQuery. I'm using the below code:

$('#my-table tr td:nth-child(7),th:nth-child(7)').hide()

The code is working, it's hiding the column of the table, however is not respecting the table id selector, it's applying the change for all the tables in the current document.

What should I change in order to have it working as expected?

Upvotes: 0

Views: 58

Answers (2)

dippas
dippas

Reputation: 60553

You need to specify the id for both selectors, otherwise the th:nth-child(7) it will hide every th:nth-child(7) you might have in your code

$('#my-table tr td:nth-child(7), #my-table th:nth-child(7)').hide()

You can also simplify this by using the find() method

$('#my-table tr').find('td:nth-child(7), th:nth-child(7)').hide()

EDIT

as pointed out by @A. Wolff this can be even more simplified using just this:

$('#my-table tr > :nth-child(7)').hide()

Upvotes: 2

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can use comma separated multiple selectors but it should be the complete selector.

$('#my-table tr td:nth-child(7),#my-table th:nth-child(7)')

or find() method with multiple inner element selector

$('#my-table tr').find('td:nth-child(7),th:nth-child(7)')

Upvotes: 1

Related Questions