JQuery: how to select parent table for parsing

I have a JS function that parses a table:

// id contains a message id, activeRow is "this" from onClick on tr
function doSomething ( id, activeRow ) {
    // AJAX calling using id as parameter
    $("#searchResultTable > tbody > tr").each(function(index) {
        $(this).removeClass("bold");
    });
}

      

This works great (thanks to Ariel @ another post ), but I thought there must be another possibility, for example:

var table = $(activeRow).parent();
$("tbody > tr", table).each(function(index) {
    // .. do something
});
// The above clearly doesn't work, but should document what I'm looking for.

      

This will allow the same table ID to be used when the function works on each one separately.

Many, many thanks!

+2


source to share


4 answers


Close, would you like to use a class on a table



$("table.className tbody tr").each(function() {
    // .. do something
});

      

+1


source


jQuery's parent () method binds the parent table:



$(activeRow).parents('table')[0];

      

+5


source


What about:

$(activeRow).siblings().andSelf().removeClass("bold")

      

This will take <tr>

in activeRow

, take it sibling <tr>

and remove the class "bold"

from all of them.

+3


source


Better to use closest

like this:

$(activeRow).closest('table')[0];

      

From here: http://api.jquery.com/closest/

closest: traverses the DOM tree until it finds a match for the supplied selector.

parents: moves the DOM tree to the root of the document, adding each ancestor element to a temporary collection; it then filters this collection based on the selector, if supplied.

In this case, it is quite possible that it parents

gets the topmost table where there is more than one in the DOM tree, where it closest

gets the one you are actually trying to work on.

+3


source







All Articles