Substitution solution based on element id attribute
Yes it is possible. This directly answers your question without relying on third-party JavaScript or APIs or attributes other than the element identifier. Also you do not need to use class =
Custom Method Call Example
// Uses JavaScript regex features to search on id= attribute var arrMatches = document.getElementsByRegex('^statusMessage_.*');
Gets an array containing all elements that have an identifier starting with "statusMessage_" (even nested).
Implementation Example - Reusable and General
Here is an implementation of the getElementsByRegex function that searches for the DOM for a given regular expression, starting with document . It is attached to the document object for convenience and in accordance with the expected behavior.
<head> <script> // Called as: document.getElementsByRegex("pattern"). // Returns an array of all elements matching a given regular expression on id. // 'pattern' argument is a regular expression string. // document['getElementsByRegex'] = function(pattern){ var arrElements = []; // to accumulate matching elements var re = new RegExp(pattern); // the regex to match with function findRecursively(aNode) { // recursive function to traverse DOM if (!aNode) return; if (aNode.id !== undefined && aNode.id.search(re) != -1) arrElements.push(aNode); // FOUND ONE! for (var idx in aNode.childNodes) // search children... findRecursively(aNode.childNodes[idx]); }; findRecursively(document); // initiate recursive matching return arrElements; // return matching elements }; </script> </head>
There are probably more efficient implementations, but this gives a start. The body of the function can be replaced with other algorithms to taste.
Check code
Finally check it out using HTML layout with nested elements like
<body> <div id="statusMessage_1">1</div> <div id="statusMessage_2">2 <div id="content">other stuff</div> <div id="statusMessage_3">3</div> </div> <script> </script>
This HTML block contains three elements starting with id="statusMessage_ ; therefore, the alert test will say
"Found 3 matches - expected 3"
Add-on Information for Variations
If you want to restrict the search to only div elements or some other specific element, then you will want to enter the following getElementByTagName code in the algorithm to limit the set of elements that have been distorted.
var arrDivs = document.getElementsByTagName("div");
You might want to change the general algorithm by passing the tag name in the second argument for filtering before the search starts as follows
var arrMatches = document.getElementsByRegex('^statusMessage_.*', 'div');