views:

151

answers:

3

I'm trying to write a reusable function to retrieve all data in a table that is passed to it and store it in an array.

I'm not sure how to pass the reference to the table.

I could do something like...

passTableRef($('#tableId th'),$('#tableId td'));

but I would like to pass just the table reference in case I would like to elaborate on the function.

Is there a way to pass $('#tableId') and append the reference to $('#tableId th') and $('#tableId td') within the function?

EDIT: for clarification

I am wondering if you can take a reference - $(#tableId)

pass it to a function - reusableFunction($('#tableId'))

then do something like this..

function reusableFunction(table)
{
  //change the selector $("#tableId") to $("#tableId th")
}
+1  A: 

Pass in just the table and just continue down to whatever you want with find.

someFunc( $('#tableId') );

then...

function someFunc( table ) {
  var tds = table.find('td');
}
thenduks
FYI, you don't need the whole jQuery object all over again; $('#foo').add('.bar') works fine too.
John Feminella
True, edited my answer not to use add anyway, though :)
thenduks
A: 

If you just want a reference to the specific table, the identifier should be all you need: $('#tableId') refers exactly to the table. If you need to refer to more specific parts later, just take that jQuery object inside your function and look at the th or td parts with add("td") or add("th").

John Feminella
A: 

If you have a jQuery object you can call find() with a selector to find descendant elements. So you could have a function something like this:

function findTableElements(table) {
  var th = $(table).find('th');
  var td = $(table).find('td');
}

and use it like so:

findTableElements($('#tableId'));

More info on the find function can be found in the docs http://docs.jquery.com/Traversing/find#expr

John Duff