jQuery - selecting elements from inside a element

JqueryJquery SelectorsParent Child

Jquery Problem Overview


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 ?

Jquery Solutions


Solution 1 - Jquery

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

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

#Take a look#

Solution 2 - Jquery

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")

Solution 3 - Jquery

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();

Solution 4 - Jquery

Why not just use:

$("#foo span")

or

$("#foo > span")

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

Solution 5 - Jquery

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

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

Solution 6 - Jquery

> ....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

Solution 7 - Jquery

both seem to be working.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JqueryJishnu A PView Answer on Stackoverflow
Solution 2 - JqueryPranay RanaView Answer on Stackoverflow
Solution 3 - JquerySai Kalyan Kumar AkshinthalaView Answer on Stackoverflow
Solution 4 - JqueryhunterView Answer on Stackoverflow
Solution 5 - JqueryCodyView Answer on Stackoverflow
Solution 6 - JqueryMohd Abdul MujibView Answer on Stackoverflow
Solution 7 - JqueryNaftaliView Answer on Stackoverflow