Javascript - Search elements by their IDs

January 2017

This tip will show you how to search for elements based on their ID. That is when the latter match a regular expression.


You already know the getElementById(id) method that is used to return the element related to a particular ID (since ID is necessarily unique) and the getElementsByTagName(tagName) method that returns an array containing all elements with the mentioned tag.

Well there are some cases where these solutions are not enough.

For example: you have squares on your site: when the user clicks a button, each square changes size, each with a new size of its own. So you'll need to have a list of their IDs to manage them. Two solutions are available:
Each time you add a square, you manually increment a list of IDs.
You have a loop that search the document to find the squares, thus the method fits directly to the code. But how to retrieve all the IDs, knowing that you do not know the exact number of squares (not loop) and you do not know where they are in the page ?


We shall be using the getElementByRegexId method. This method has two parameters, namely:
The regular expression that matches the IDs.
[Fac] The name of the tag to be searched. If nothing is indicated, then all the tags shall be taken into consideration.

The principle is simple: we search through the elements retrieved by getElementsByTagName, test the IDs and anything that match the regular expression, is added to a table:

function getElementsByRegexId(regexpParam, tagParam) {  
    // Si aucun nom de balise n'est spécifié, on cherche sur toutes les balises  
   tagParam = (tagParam === undefined) ? '*' : tagParam;  
   var elementsTable = new Array();  
   for(var i=0 ; i<document.getElementsByTagName(tagParam).length ; i++) {  
    if(document.getElementsByTagName(tagParam)[i].id && document.getElementsByTagName(tagParam)[i].id.match(regexpParam)) {  
   return elementsTable;  

var divCarres = getElementsByRegexId(/_carre.*/, "div");  
var tousLesCarres = getElementsByRegexId(/_carre.*/);


Published by jak58. Latest update on September 29, 2011 at 07:49 AM by jak58.
This document, titled "Javascript - Search elements by their IDs," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (