ronilondon ronilondon - 2 months ago 10x
Javascript Question

Add and remove class in table rows JQuery

I have a hierarchal table where I am adding first class name dynamically. I want to add another class (for example –

) when user click a row and remove when click again. If not click again in the same row then it will be remain same (
) and if click into another row, it will add active class there. I do not want to use
because I already used this in another function. The code I tried, is not working properly.

My table structure is –

<table id="tbl_data">
<tr class="t1" ><td><div><a href="#">test1</a></div></td></tr>
<tr class="t2" ><td><div><a href="#">test2</a></div></td></tr>
<tr class="t3" ><td><div><a href="#">test3</a></div></td></tr>

var lvl = '@h_lbl'; (eg: cls1)

$('table#tbl_data tbody tr.' + lvl).on('click', function (event) {

if ($(this).hasClass('active'))

Thanks in advance


You can use this :

var table = $('#tble_data');    

table.on('click', 'tr', function () {

    if ( $(this).hasClass('active') ) {