124

let's say I have a markup like this:

<div id="foo">
  ...
  <span id="moo">
    ...
  </span>
  ...
</div>

and I want to select #moo.

why $('#foo').find('span') works, but $('span', $('#foo')); doesn't ?

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
Alex
  • 66,732
  • 177
  • 439
  • 641
  • 10
    Why not `$('#moo')` ? ;) Btw. it does work: http://jsfiddle.net/fkling/k5X2r/ – Felix Kling Apr 27 '11 at 18:15
  • I dont' know why but the function I hook to the selected span gets applied to all spans in the page, not just the one inside #foo :( – Alex Apr 27 '11 at 18:31
  • 3
    What about when you already have the element selected in a var, so for example you start with `var ele = $("div #foo")` how can you get to moo from here (without using array references) – Worthy7 Aug 03 '16 at 05:03

7 Answers7

158

You can use any one these [starting from the fastest]

$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")

Take a look

Jishnu A P
  • 14,202
  • 8
  • 40
  • 50
96

Actually, $('#id', this); would select #id at any descendant level, not just the immediate child. Try this instead:

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

or

$("#foo > #moo")

or

$("#foo > span")
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • That won't select anything because the element has the **ID** `moo`, not the class. – Felix Kling Apr 27 '11 at 18:16
  • 7
    It's worth noting that `.children()` and `.find()` are similar except that the former travels only one level down the DOM sub-tree. – Kevin May 26 '16 at 03:13
32

You can use find option to select an element inside another. For example, to find an element with id txtName in a particular div, you can use like

var name = $('#div1').find('#txtName').val();
11

Why not just use:

$("#foo span")

or

$("#foo > span")

$('span', $('#foo')); works fine on my machine ;)

hunter
  • 62,308
  • 19
  • 113
  • 113
9

Have a look here -- to query a sub-element of an element:

$(document.getElementById('parentid')).find('div#' + divID + ' span.child');

Matthieu Charbonnier
  • 2,794
  • 25
  • 33
Cody
  • 9,785
  • 4
  • 61
  • 46
6

....but $('span', $('#foo')); doesn't work?

This method is called as providing selector context.

In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

eg.

$("span",".cont1").css("background", '#F00');

The above line will select all spans within the container having the class named cont1.

DEMO

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
2

both seem to be working.

see fiddle: http://jsfiddle.net/maniator/PSxkS/

Naftali
  • 144,921
  • 39
  • 244
  • 303