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?
-
you wanted a jQuery answer and choosed a JS one :(Elzo Valugi– Elzo Valugi2009-09-14 11:07:18 +00:00Commented Sep 14, 2009 at 11:07
-
@Elzo, there wasn't a satisfactory jq solution unfortunately.James L– James L2009-09-14 11:43:19 +00:00Commented 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. :)davidethell– davidethell2012-03-19 21:01:18 +00:00Commented Mar 19, 2012 at 21:01
Add a comment
|
6 Answers
You could just join them, like this:
var ids = ['div1', 'div2', 'div3'];
$('#' + ids.join(',#')).click(function() { alert('hi'); });
1 Comment
Alan Alcock
Now we're cooking on gas!
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
Oleh Prypin
JavaScript is really lame.
$.map(ids, document.getElementById) doesn't work indeed!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.