I'm refactoring some code at the moment and have come across a selector:
jQuery("tr","#ctl00_MainContent_MyUserControl").each(function(i,row) { ... }
It looks like it's selecting <tr>
's from the user control on the page (ignore the fact that the instance is fully named!) but it's not a syntax I'm familiar with and can't find anything in the documentation. I'd expect it to be written:
$("#ctl00_MainContent_MyUserControl tr").each(function(i,row) { ... }
Can anyone tell me if there's a difference (subtle or otherwise) that I'm missing here??
This selector selects all
tr
elements inside an element with idctl00_MainContent_MyUserControl
. It is exactly the same as your second example.The second parameter provides a context for the first parameter. There are better use cases for this syntax, for example:
Where
el
is some element on your page. In this case, you can't use the second syntax form.The second argument to the jQuery constructor (when the first is a selector) is the context.
From the API docs
See http://api.jquery.com/jQuery/
It's exactly the same. It could also have been written:
The syntax for the former can be seen in the jQuery constructor documentation. It's basically "find all elements that matches the first selector, that's a descendant of the second matched by the second".
Calling the
jQuery()
method with two arguments (selector
andcontext
) is equivalent tojQuery(context).find(selector)
. Thus:is equal to:
which also happens to be the same as:
My personal opinion is that the use of
context
only makes sense when you can pass an already selected element (jQuery
orDOM
), not so much when you just pass a selector (String
). In that case I simply prefer to mimic the CSS selector: e.g.,#ctl00_MainContent_MyUserControl tr
.