-1

If I wanted to find an element on the page, I would use $('#Foo');

Now, I have a scenario where my 'this' context is a jQuery element. I would like to find an element underneath 'this.'

I am using:

$(this).find('#Foo');

I just wanted to make sure there wasn't a cleaner way of expressing this. If I wasn't in my this context, I might use something like $('#this #Foo'). It seems surprising that my jQuery selector query gets longer when I have an explicit reference to the 'this' jQuery element.

Sean Anderson
  • 27,963
  • 30
  • 126
  • 237

4 Answers4

2

first off, since element ids are unique to the document, you don't need to find one within the context of another element.. but for a nice syntax, I like

$('.foo', this) which will find all children with class "foo"

ilan berci
  • 3,883
  • 1
  • 16
  • 21
1

The .children() is faster than .find().

$(this).children('#Foo');

Explanation

Reason is, .children() only looks at the immediate children of the node, while .find() traverses the entire DOM below the node, so .children() should be faster given equivalent implementations. find uses native browser methods, however, while children uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.

References

  1. What is fastest children() or find() in jQuery?
  2. Traversing .children()
  3. Traversing .find()
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

IDs should be unique, so the quickest way to select #Foo in jQuery would simply be

$('#Foo')

To answer your question, the .children() method is faster than .find() in most browsers, and it works the same as long as you're dealing with direct descendants.

$(this).children('#Foo')

I put together a JSPerf which demonstrates this. Keep in mind that in most cases the performance difference is negligible.

zxqx
  • 5,115
  • 2
  • 20
  • 28
  • How come children is faster when dealing with direct descendants? I would expect find to perform a breadth-first search... the first level's iteration being the same as .children()'s ? – Sean Anderson Feb 08 '13 at 18:41
  • @SeanAnderson And then it continues down to every other level unnecessarily, wasting time looking where it will find nothing. – James Montagne Feb 08 '13 at 18:42
0

If you're finding an element by id, you shouldn't need to preselect $(this). Element ids should be unique. No two elements should have the same id. That said, if you're selecting by something else, like class, you'll need to use $(this).find(".myclass") to select subelements.

turiyag
  • 2,757
  • 2
  • 22
  • 21