I need to select first table and then second table from the html in string. I know this can be done by selector :eq(0) and :eq(1), but
var firstTable = $("table", "<table></table>").length;
firstTable == 0. Why?
When you pass a second argument to jQuery() (aka $()), you are specifying a context to search within. That is, this:
$(selector, context);
is equivalent to this:
$(context).find(selector);
So, you could rewrite your "broken" code like this to show why it's not finding a table element:
var firstTable = $("<table></table>").find("table").length;
...because .find() selects descendant elements only.
.find() works with all of the selectors that $() does.Try it like this to illustrate the problem:
var firstTable = $("table", "<div><table></table></div>").length;
// returns 1
The search happens within the context argument.
context-style selecting, but you're definitely right about being able to pass in an HTML string - which makes sense, anyway, when you realize that $(selector, context) is equivalent to $(context).find(selector). Time to edit my answer. +1x.find(y).