Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub-select with a variable in JQuery

Tags:

jquery

Let's say that I have a ul with a series of li in it.

I store the ul as a JQuery variable, like so var myUl = $("ul")

Now I want to select all the li contained in myUl.

Now, I realize that in this specific example I could do, $(myUl).children(); but I'm wondering how I could do something like this: $(myUl + "li") and have it work? What's the syntax for combining a variable and other text?

Or do I have to make a new variable that says var newUl = $("ul li")?

like image 486
Hanna Avatar asked Nov 20 '25 17:11

Hanna


2 Answers

You need to pass the myUl as the context in the selector.

$("li", myUl)

Sample FIDDLE

To quote the docs

Internally, selector context is implemented with the .find() method, so $( "span", this ) is equivalent to $( this ).find( "span" ).

In other words, passing the context to the selector is the same as doing myUl.find('li')

like image 61
Blake Plumb Avatar answered Nov 25 '25 00:11

Blake Plumb


myUl.find("li");

or

myUl.children("li");

find will get all descendants whereas children is just direct children.

like image 27
James Montagne Avatar answered Nov 24 '25 22:11

James Montagne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!