Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of IDs - how to select with JavaScript / JQuery?

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?

like image 856
James L Avatar asked Sep 14 '09 10:09

James L


2 Answers

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);
like image 197
Maine Avatar answered Sep 29 '22 02:09

Maine


You could just join them, like this:

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

$('#' + ids.join(',#')).click(function() { alert('hi'); });
like image 29
Greg Avatar answered Sep 29 '22 00:09

Greg