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.getElementById('statusMessage_*')
.
This is because until the page is generated, I don't know the suffix of the ID and only one such ID will be present in a page. Is this possible?
Thanks for any help.
* wildcard also known as containing wildcard. [attribute*=”str”] Selector: The [attribute*=”str”] selector is used to select that elements whose attribute value contains the specified sub string str. This example shows how to use a wildcard to select all div with a class that contains str.
Asterisk (*): It is used for replacing 1 or more characters from a selector attribute. For Eg. <title="abc-zyx"></title> is an attribute which changes dynamically, every time you open a specific webpage.
The universal selector is used as a wildcard character.
You can use "wildcards" if your file names/directories follow a pattern, then you can make a loop to write them automatically instead of manually. ./ for files in the current directory, ../ for files one directory above and * for all matches e.g. <img src="../../content/images/IMG_*.
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With