Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - selecting elements from inside a element

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 ?

like image 238
Alex Avatar asked Apr 27 '11 18:04

Alex


People also ask

How do I find the element inside a div?

You can use the children property of getElementById() method in JavaScript to get or extract unique ids of all the DIV elements inside a DIV element.

How do I select elements when I already have a DOM element?

If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object. var myDomElement = document. getElementById( "foo" ); // A plain DOM element.

How do I select a tag within a div?

Use document.querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div. Therefore, innerDiv is the div with the class myclass .

What is $element in jQuery?

Description: Selects all elements with the given tag name.


2 Answers

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

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

Take a look

like image 51
Jishnu A P Avatar answered Sep 16 '22 23:09

Jishnu A P


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") 
like image 33
Pranay Rana Avatar answered Sep 20 '22 23:09

Pranay Rana