Find all elements whose id begins with a common string

javascript, regex

Solution

Using jQuery you can use the attr starts with selector:

var dates = $('[id^="createdOnid"]');

Using modern browsers, you can use the CSS3 attribute value begins with selector along with `querySelectorAll`:

var dates = document.querySelectorAll('[id^="createdOnID"]');

But for a fallback for old browsers (and without jQuery) you'll need:

var dateRE = /^createdOnid/;
var dates=[],els=document.getElementsByTagName('*');
for (var i=els.length;i--;) if (dateRE.test(els[i].id)) dates.push(els[i]);

Problem

I have a XSL that created multiple elements with the id of "createdOn" plus a $unique-id ``` Example : createdOnid0xfff5db30 ``` I want to find and store these in a variable using JavaScript. I've tried ``` var dates = document.getElementsById(/createdOn/); ``` but that doesn't appear to work.

Original source

Related problems