Javascript - Search elements by their IDs
This tip will show you how to search for elements based on their ID. That is when the latter match a regular expression.
Issue
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 ?
Solution
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
Example:
var divCarres = getElementsByRegexId(/_carre.*/, "div"); var tousLesCarres = getElementsByRegexId(/_carre.*/);