How to select a div using it\'s ID but with a widcard?
If the DIV\'s ID is statusMessage_1098
, I would like to select it in some way like document
Just thought it was worth updating the thread with a more recent way of doing this in JavaScript as was still coming up in searches.
document.querySelector("[id^='statusMessage_']");
caniuse.com lists it can be used on IDs from IE8 and great support in other browsers.
Usual way to do this within css is to give the elements a class 'statusMessage' in addition to their unique ids. Then you can create a css rule with a selector that will affect all elements with that class. Eg
.statusMessage {color: red;}
Remember that elements can have more than one class. Eg
<p id="id123" class="class1 class2">
If you don't want to use jQuery then there is another easier way to do this:
Assign a class
- for an example name it "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 how 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);
}
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";
with whatever CSS you want to apply to all divs that have an id that starts with statusMessage_.
I'm not sure how you're populating it but if it's from the code behind you could try something like:
document.getElementById('statusMessage_<%= generatedID %>')
where generatedID is the ID generated from the code behind.
Using jQuery you can do this
$("div[id^='statusMessage_']")
See attributeStartsWith
Edit - with class name selector
If you can use a class name then you can use something like this
$$('div.myDivClass');
gets all div elements with class 'myDivClass'