Reputation: 4187
I have this sample code:
<div id="click-test-1">Click test 1</div>
<div id="click-test-2">Click test 2</div>
In jQuery I use this code:
jQuery("div[id^=\'click-test\']").click(...);
How can I get the same thing in basic JavaScript?
Upvotes: 0
Views: 1544
Reputation: 15205
This is not the direct answer to your question, but why don't you just use classes? getElementByClassName will get the job done.
<div id="click-test-1" class="click_me">Click test 1</div>
<div id="click-test-2" class="click_me">Click test 2</div>
Something like this (I haven't tested it):
var collection = document.getElementsByClassName('click_me');
for(var i=0, leng=collection.length; i<leng; i++)
{
collection[i].click();
}
Maybe I'm not taking into account your whole context, but I would say using id for grouping elements is a bad practice.
Upvotes: 1
Reputation: 95315
So you're looking to do this in vanilla Javascript, without the jQuery library loaded? Because jQuery is Javascript.
If you don't have to worry about supporting older browsers (notably IE7 and under), you can use document.querySelector
(to get a single matching element) or document.querySelectorAll
(to get an array of all matching elements) to look up elements by CSS selectors:
var elems = document.querySelectorAll("div[id^=\'click-test\']")
for (var i=0; i<elems.length; ++i) {
elems[i].click()
// Note that click() is also browser/element-type-dependent without jQuery
}
If you do have to worry about supporting other browsers, then there's really no way but to do a document.getElementsByTagName('div')
and then loop over the result checking each element's id against a regex.
var elems = document.getElementsByTagName('div')
for (var i=0; i<elems.length; ++i) {
if (elems[i].id.match(/^click-test/)) {
elems[i].click()
}
}
In the particular case of looking for a prefix, you can use Gabe's substring test instead of a regex.
Upvotes: 5
Reputation: 50503
You don't need a regex if you're just looking to get all <div>
's that have an id that starts with some string... You could simply do it like this:
var children = document.body.getElementsByTagName('div');
var elements = [], child;
for (var i = 0, length = children.length; i < length; i++) {
child = children[i];
if (child.id.indexOf("click-test") == 0)
// if you want to use a regex, just replace this condition with
// if (child.id.match(/^click-test/))
elements.push(child);
}
Upvotes: 1