Select a div using a wildcard

How to select a div using its ID, but using a view map?

If the div identifier is statusMessage_1098 , I would like to select it like document.getElementById('statusMessage_*') .

This is because until the page is generated, I do not know the identifier suffix, and only one such ID will be present on the page. Is it possible?

Thanks for any help.

+4
source share
8 answers

Using jQuery you can do it

 $("div[id^='statusMessage_']") 

See attributeStartsWith

Edit - Using the Class Selector

If you can use a class name, you can use something like this

 $$('div.myDivClass'); 

gets all div elements with class 'myDivClass'

+12
source

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> // a quick test to see if you get the expected result. var arrMatches = document.getElementsByRegex('^statusMessage_.*'); alert('found ' + arrMatches.length + ' matches - expected 3.') </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"); // pull all divs from the doc 

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'); 
+17
source

In jquery, the easiest way is to assign a class for each div let say 'statusMessage' something like:

 <div id="statusMessage_<%=someid%>" class="statusMessage">...</div> 

To get them all:

 $('.statusMessage') // or $('div.statusMessage') //or $('div[id^=statusMessage_]') 

Without jquery:

 var divs = document.getElementsByTagName('div'); for(var i=0;i<divs.length;i++){ if(divs[i].id.indexOf('statusMessage_')==0){ //do stuff here for every divs[i] } } 
+2
source

I just thought it’s worth updating the stream using a more recent way to do this in JavaScript, as it still occurred while searching.

 document.querySelector("[id^='statusMessage_']"); 

caniuse.com lists it can be used in IDs from IE8 and excellent support in other browsers.

+2
source
 function switch2 (elementid) { var divs = document.getElementsByTagName("div"); for ( var i = 0; divs[i]; i++ ) { if (divs[i].id.indexOf("statusMessage_") == 0) { document.getElementById (divs[i].id).style.display = "none"; } } } 

Just replace document.getElementById (divs[i].id).style.display = "none"; on any CSS that you want to apply to all divs that have an id that starts with statusMessage _.

+1
source

I'm not sure how you populate it, but if it is from the code behind you, it might try something like:

 document.getElementById('statusMessage_<%= generatedID %>') 

where the generated ID is the identifier generated from the code behind.

0
source

The usual way to do this in css is to provide elements of the statusMessage class in addition to their unique identifiers. Then you can create a css rule with a selector that will affect all elements of this class. For instance,

  .statusMessage {color: red;} 

Remember that elements can have more than one class. For instance,

 <p id="id123" class="class1 class2"> 
0
source

If you do not want to use jQuery, then there is another easy way to do this:

Assign a class - for the example name this is a "message" and use the following:

 function getElementsByClass(searchClass,node,tag) { var classElements = new Array(); if ( node == null ) node = document; if ( tag == null ) tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } } return classElements; } 

Here is what you call it:

 var messages = getElementsByClass("message"); for(var index=0; index < messages.length; index++) { // prompt the content of the div //alert(message[index].innerText); } 
0
source

All Articles