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")?
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')
myUl.find("li");
or
myUl.children("li");
find will get all descendants whereas children is just direct children.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With