deharodk deharodk - 1 year ago 84
jQuery Question

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?

Answer Source

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()


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

$('#my-table tr > :nth-child(7)').hide()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download