1

I have seen it here. What is meant by tbl in the following statement? What does it imply?

var rows = $('tr', tbl);
Community
  • 1
  • 1
Solace
  • 8,612
  • 22
  • 95
  • 183

2 Answers2

4

The tbl in the above is another dom element. This is passed in as the (optional parameter) context:

jQuery( selector [, context ] )

...for the selector, in this case 'tr'.

source


So essentially this:

$('tr', tbl);

says return me everything that matches the selector 'tr' in the element(s) tbl.


Example

So given

<table>
  <tr>first</tr>
<table>
<table id="test">
   <tr>second</tr>
</table>

This returns varying results:

//context is global
$('tr') => first & second

//restrict the context to just the second table 
//by finding it and passing it into the selector
var tbl = $('#test');
$('tr', tbl) => just second
Liam
  • 27,717
  • 28
  • 128
  • 190
  • why selector is written as `selector [` and context as `context ]` in `jQuery( selector [, context ] ` ? I am sure there must be some thought behind it? – user3198603 May 25 '16 at 08:24
  • context is optional so it's `[,context]` (i.e. context is an optional parameter) . selector is not optional so it's not in square braces. @user3198603 – Liam May 25 '16 at 08:50
2

This pattern is using jQuery context. Your query is used to find the rows within the table.

var tbl = $("table#tableId"); // this line provides the context
var rows = $("tr", tbl); // finding all rows within the context

This is equivalent to writing

var rows = tbl.find("tr")

There is good explanation on using jQuery context in this SO Question here

Community
  • 1
  • 1
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56