using variables within a jquery selector

mheavers picture mheavers · Jan 28, 2011 · Viewed 42.3k times · Source

I'm trying to build a dynamic jquery selector with the following code:

var section_id = "{segment_3}";
var num_children = $('#'+ section_id + ' ul').children().size();

where segment_3 is a value I successfully retrieve from the url string, which, for example, might return the value of "section_one"

But when trying to create the variable num_children, this reference doesn't work. How do I construct the code to build a dynamic reference? Thanks for any help.

Answer

Kamil Sarna picture Kamil Sarna · Jan 28, 2011

Assuming var section_id = 'section_1' this:

$('#'+ section_id + ' ul').children().size();

will give you

$('#section_1 ul').children().size();

and yes, this is valid as well. It will give you all ul elements within #section_1 element (no matter how deep they would be). Probably you'll get array of elements and calling .children() on it is also fine. It should all work.