user1977591 user1977591 - 7 months ago 13
Javascript Question

Need help traversing elements with jQuery in ASP.NET Web Forms

what my page looks like

enter image description here

So the first image is what my page looks like. I am trying to grab the ID of the table at the top (the table that has the class trackingHistory and ID of ContentPlaceHolder1_ctl00_myRpt_ctl00_0_gdvTH_0) whenever the highlighted button is clicked.

Right now I can click the button and fire my Javascript method 'ToggleHistory()' and use jQuery to get the ID of my button. (.attr('id'))

but that's about as far as i can get. I have tried messing around with the closest() and prev() methods from jQuery but haven't had any luck. any help would be appreciated.

javascript method

function ToggleHistory(button)
{
console.log(button);
var x = $(button).prev();
var y = $(button).closest('table').find('.trackingHistory');
//var z = $(button).closest('.trackingHistory');

console.log(x);
console.log(y);
console.log($(y).attr('id'));
//console.log(z);
}


i dont want to have to hard code the id because there will be a dynamic amount of these tables and buttons.

Answer

The <button> and the <table> don't have a direct relationship, but do have the <div> in common.

<div>
  <table class="toggleHistory"></table>
</div>
<button type="button" onclick="ToggleHistory(this)">click here to hide</button>

The <button> and <div> are immediate siblings, which you can traverse between with .prev() and back with .next().

$(button).prev()...

Then, the <div> and <table> are .parent() and child (.children()):

$(button).prev().children('.trackingHistory');

function ToggleHistory(button)
{
    console.log(button);

    var $historyTable = $(button).prev().children('.trackingHistory');

    console.log($historyTable.attr('id'));
}