Reputation: 68406
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 ?
Upvotes: 132
Views: 375212
Reputation: 13908
....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
.
Upvotes: 7
Reputation: 11844
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();
Upvotes: 40
Reputation: 10015
Have a look here -- to query a sub-element of an element:
$(document.getElementById('parentid')).find('div#' + divID + ' span.child');
Upvotes: 9
Reputation: 14382
You can use any one these [starting from the fastest]
$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")
Upvotes: 166
Reputation: 176896
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")
Upvotes: 106
Reputation: 63512
Why not just use:
$("#foo span")
or
$("#foo > span")
$('span', $('#foo'));
works fine on my machine ;)
Upvotes: 11
Reputation: 146302
both seem to be working.
see fiddle: http://jsfiddle.net/maniator/PSxkS/
Upvotes: 2