D'OH!! I'd not thought of that, but as you point out, the selector is a string, so it should have occurred to me at some point. Thanks to yourself and Josh for the replies. As it happens, this is a FAQ for a number of programming languages I've used, and I usually end up hunting for an eval() or similar function - this is a lot simpler than many.
Cheers Fred On Oct 27, 9:39 pm, "Josh Nathanson" <[EMAIL PROTECTED]> wrote: > You want this: > > $("#" + fieldset_id); > > Don't feel bad, that trips up a lot of people at first (myself included). > > Basically the selector is just a string, so you can use the usual JS string > methods to get what you need. > > -- Josh > > ----- Original Message ----- > From: "fredriley" <[EMAIL PROTECTED]> > To: "jQuery (English)" <jquery-en@googlegroups.com> > Sent: Monday, October 27, 2008 1:13 PM > Subject: [jQuery] Selecting an element whose ID is in a variable > > > This has got to be a FAQ, but I can't see it in the FAQ so here goes, > > and apologies if it's a stupid question but I'm a relative newbie to > > jQuery: > > > How can I select an element whose id is stored in a constructed string > > variable? > > > What I mean is something like the following. In a document I've got > > <span> elements with IDs "1", "2", "3", etc, and these correspond to > > fieldset elements with IDs "part1", "part2", "part3", etc. The user > > clicks on a <span>, the code gets its ID, constructs the ID of the > > corresponding <fieldset>, then does something with that (hides it). So > > something like: > > > $("span").click(function() > > { > > // get the handle of the clicked element > > var mySpan = $(this); > > // get its id > > var span_id = mySpan.attr("id"); > > // construct the fieldset id > > var fieldset_id = "part" + span_id; > > // select the fieldset then hide it - now I'm stuck > > }); > > > I've tried the selectors: > > > alert($(fieldset_id).attr("id")); // gives 'undefined' > > alert($(#fieldset_id).attr("id")); // syntax error: illegal character, > > not surprisingly > > alert($("#fieldset_id").attr("id")); // gives 'undefined' > > > An alternative would be to get the handle of the fieldset element, > > which could be achieved with the Javascript: > > > var id2 = document.getElementById(fieldset_id); > > alert(id2.id); // gives the id of the fieldset > > > but I don't know how to do this in jQuery. I'd prefer to go the whole > > jQuery hog and not mix it with raw JS, and I could do with > > understanding how to do this simple operation anyway to improve my > > jQuery understanding, so tips would be welcome. TIA. > > > What I'm trying to do is generalise the specific code in the test at > >http://www.nottingham.ac.uk/~ntzfr/test/ajax/jquery/show_hide.htmlto > > handle a form with any number of toggle-able sections. > > > Cheers > > > Fred