tags:

views:

491

answers:

3

Hi , a js newbie here. I need to get all the objects whose id matches a specific pattern . How can I do it? Thanks!

+2  A: 

Easy with jQuery

$("*[id\^='log\_']")

--edit--

Otherwise...

var matches = [];
var elems = document.getElementsByTagName("*");
for (var i=0; i<elems.length; i++) {
  if (elems[i].id.indexOf("log_") == 0)
    matches.push(elems[i]);
}
//matches now is an array of all matching elements.
Tracker1
And if you're not using jQuery? :P
Daniel Lew
@Daniel, see update above.
Tracker1
Your jQuery selector could be improved. The "star selector" is implicit, you should be using the "starts-with" selector instead of "contains", and the underscore doesn't need escaped: `$("[id^=log_]")`
Ben Blank
@Ben, didn't remember the starts with vs. star.. :) thx.
Tracker1
A: 

It would be best to use a JS framework to accomplish this because they have advanced DOM selector functions that make what you want to do incredibly easy. There are many to choose from but the more popular are jQuery, Prototype, MooTools, and Dojo.

Stephen
+2  A: 

Ok, here's a straight JavaScript answer:

// a handy function to aid in filtering:
// takes an array and a function, returns another array containing
// only those elements for which f() returns true
function filter(a, f) 
{ 
  var ret = []; 
  for (var i=0; i<a.length; ++i) 
  {
    if ( f(a[i]) ) 
      ret.push(a[i]); 
  }
  return ret;
}

// this collects all elements in the current document
var elements = document.getElementsByTagName("*");

// and this filters out all but those that match our pattern
var logElements = filter(elements, function(el) 
  { return /log_/.test(el.id) } ); // simple expression
Shog9