Derek Adair
Derek Adair

Reputation: 21935

[jQuery]: append a selector

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")
}

Upvotes: 0

Views: 2171

Answers (3)

John Duff
John Duff

Reputation: 38598

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

Upvotes: 0

John Feminella
John Feminella

Reputation: 311765

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").

Upvotes: 0

rfunduk
rfunduk

Reputation: 30452

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');
}

Upvotes: 2

Related Questions