Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Find exact DOM elements

Tags:

html

jquery

css

this is my Html code where I want to select only next element of selected checkbox

<tr class="" role="row">
<td class="e-rowcell e-templatecell" role="gridcell" style="text-align: center;">
    <input type="checkbox" class="XAxisrowCheckbox">
</td>
<td class="e-rowcell e-hide" role="gridcell" style="text-align: left;">0</td>
<td class="e-rowcell" role="gridcell" style="text-align: left;">Location ID</td>
</tr>
<tr class="e-alt_row" role="row" aria-selected="true">
<td class="e-rowcell e-templatecell e-selectionbackground e-active" role="gridcell" style="text-align: center;">
    <input type="checkbox" class="XAxisrowCheckbox">
</td>
<td class="e-rowcell e-hide e-selectionbackground e-active" role="gridcell" style="text-align: left;">1</td>
<td class="e-rowcell e-selectionbackground e-active" role="gridcell" style="text-align: left;">Location Name</td>
</tr>

jQuery Code

 $(document).on('click', '.XAxisrowCheckbox', function () {

     $(".XAxisrowCheckbox").parent().next(this).css('background-color','red');

});

but the problem is it is applying background color to all td regardless of selected

what I am getting is enter image description here

What I expect is to change only this element which is selected enter image description here

like image 667
Ameya Deshpande Avatar asked Jan 08 '23 18:01

Ameya Deshpande


2 Answers

Its best to use closest for this:

$(document).on('click', '.XAxisrowCheckbox', function () {
    $(this).closest('td').css('background-color','red');
});

It reads much more nicely than parent and next, and should you need to you could chain on a find statement as well. For instance:

$(this).closest('td').find('a').css('color','red');

This is essentially saying "Work your way up the dom tree until you find the first td wrapping the clicked element, then go down again until you find all a elements"

EDIT : Actual Code Which Works after workaround for me

$(this).closest('td').next().css('background-color','red');
like image 52
Djave Avatar answered Feb 05 '23 15:02

Djave


Use this instead

$(document).on('click', '.XAxisrowCheckbox', function () {

     $(this).parent().next().css('background-color','red');

});
like image 22
smnbbrv Avatar answered Feb 05 '23 13:02

smnbbrv