13

I have an array of element identifiers, coming back from some server-side validation. The IDs aren't prefixed with a '#'. Rather than going through the array and prefixing a # to each member, is there jquery means of directly selecting all elements by their IDs?

3
  • you wanted a jQuery answer and choosed a JS one :( Commented Sep 14, 2009 at 11:07
  • @Elzo, there wasn't a satisfactory jq solution unfortunately. Commented Sep 14, 2009 at 11:43
  • 1
    @Elzo, I'd say his solution was a great combination of JS and jQuery. Why be stuck on jQuery-only when Javascript will do. (digging up the past. :) Commented Mar 19, 2012 at 21:01

6 Answers 6

23

You could just join them, like this:

var ids = ['div1', 'div2', 'div3'];

$('#' + ids.join(',#')).click(function() { alert('hi'); });
Sign up to request clarification or add additional context in comments.

1 Comment

Now we're cooking on gas!
14

Don't you forget "old fashioned" getElementById - it doesn't require hashing the ids. Then just feed nodes to jQuery to get a jQuery object:

var ids = ['jq-primarySearch', 'jq-n-CSS'];
var nodes = $.map( ids, function(i) { return document.getElementById(i) } );
var jqObj = $(nodes);

1 Comment

JavaScript is really lame. $.map(ids, document.getElementById) doesn't work indeed!
4

In jQuery you can select by ID like this

$("[id=id_value]"); // returns 1 id

if you name them something like id_1 and id_2 you can do this

$("[id^='id_]") // returns multiple 

Comments

4

(NB - I haven't tried this - this is off the top of my head)

Let's say your array is "arr".

Couldn't you map your array of string identifiers into an array of jQuery objects, then concantenate them all using the usual jQuery selector?

$($.map(arr, function(id) { return $('#' + id); }))

Comments

1

Just do the node selection yourself then wrap the result:

$(document.getElementById(id))

saves constructing a string selector that jQuery will only have to parse back in and then do exactly the same thing. Plus you don't have to worry about escaping characters like ‘:’ and ‘.’ which are valid in IDs but mean something else in selectors.

Comments

0

If you have the ID as a string you can select it in jQuery like this

$("#"+id); //gives you one element

If you have multiple ID's that are similar, then use Elzo's suggestion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.