0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Radek: I don't know what you mean. .find() works with all of the selectors that $() does.
1

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.

2 Comments

Hm, I don't usually use the 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. +1
@Matt, I don't use it much either; I too prefer the flow of x.find(y).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.