tags:

views:

61

answers:

5
+2  Q: 

ID/Class Selector

Hi. I have some kind of problem with jQuery selectors.

Let's say i want to select $('#elementID') but the elementID is a variable.

There is any other possiblity to do this other way than var variable = elementID; $('#'+variable) ? I mean without specifying the # anywhere else?

Thanks!

+3  A: 

The following is probably the fastest and the cleanest solution:

$(document.getElementById(elementID))

Appending your variable to "#" would work of course, but it's inherently slower.

Philippe Leybaert
+1 for using standard DOM methods where appropriate. With `getElementById` you don't have to worry about the ID maybe having `.` (or `:`) characters in that would break the selector string if unescaped.
bobince
the problem is i want to REMOVE things from the source, not to add :) Besides that, i think jQuery uses standard selectors where is available.
Ionut Staicu
I don't see where this makes a difference. If it does, I probably read your question wrong.
Philippe Leybaert
+1  A: 

Not sure what you mean, but:

var variable = '#' + elementID;

$(variable)...
Tatu Ulmanen
is the same thing as i wrote before...
Ionut Staicu
+2  A: 

Not really, no. You need "#" as a selector to select an ID. No reason to not use the ID selector. Or you could write your own function, something like:

$.id = function(id)
{
    return $("#" + id);
}

var elementID = "elementID";
$.id(elementID).text();

That would return an element with the ID of "elementID" without having to use the "#". Kind of pointless though.

Typeoneerror
Pointless, true, but it would have been nice if a simple function to get a single element by id would be in the core jQuery library. +1
Philippe Leybaert
i like this solution :)
Ionut Staicu
+1  A: 

If elementID is a variable ala var elementID = '#someId', I would suggest simply (although I didn't try it ):

$(elementID)

jQuery/JavaScript should dereference this variable as a string value and wrap the ID correctly for further operations...

John K
+1  A: 

I use $('#'+variable) all the time.

morgancodes
I also use this format. But it seems is not too... elegant :)
Ionut Staicu