Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select div using wildcard ID

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.

like image 321
Nirmal Avatar asked Dec 21 '09 05:12

Nirmal


People also ask

How to use wildcard in CSS selector?

* 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.

What is the purpose of * wildcard in a selector?

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.

Which selector is used as a wildcard selector?

The universal selector is used as a wildcard character.

How do you do a wildcard in HTML?

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_*.


2 Answers

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'

like image 71
rahul Avatar answered Sep 25 '22 05:09

rahul


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.

like image 26
itsvicki Avatar answered Sep 26 '22 05:09

itsvicki