14

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

Yossale
  • 14,165
  • 22
  • 82
  • 109

3 Answers3

20

Current Browsers:

// DOM collection as proper array
const matches = Array.from(document.querySelectorAll('[id^=log_]'));

Older Browsers: (IE9+)

// Use Array.prototype.slice to turn the DOM collection into a proper array
var matches = [].slice.call(document.querySelectorAll('[id^=log_]'));

jQuery:

$('[id^=log_]')

Really Old Browsers, no jQuery:

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
  • 19,103
  • 12
  • 80
  • 106
  • 2
    And if you're not using jQuery? :P – Dan Lew Apr 23 '09 at 20:55
  • 2
    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 Apr 23 '09 at 21:24
  • @openwonk I try to curate my answers when I notice upvotes or comments and they're dated... :-) Looking forward to Array.from being more commonly available. – Tracker1 May 24 '16 at 22:31
  • This brings me too close to what I am looking for. When I logged this object in console, I observed that it prints the entire object and not the ID (which is available when I expand the object). Any ideas on how I can fetch just the ID ? – Yash Saraiya May 10 '18 at 11:06
  • 1
    @YashSaraiya way late on a response, but `matches.map(m => m.id)` will give you the list of IDs – Tracker1 Jul 05 '18 at 21:00
  • There is a complete answer here: https://stackoverflow.com/questions/8714090/queryselector-wildcard-element-match – eric_the_animal Feb 24 '23 at 19:36
3

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
  • 156,901
  • 35
  • 231
  • 235
-1

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 Walcher
  • 2,565
  • 1
  • 21
  • 22