I have html, like this:
<div id="c0" class="bz_ment bz_first_ment"></div>
<div id="c1" class="bz_ment"></div>
<div id="c2" class="bz_ment"></div>
<div class="bz_add_ment"></div>
How can I get array of all the div's (3 div in example) by class that's starts with "bz_ment[anysymbols]" in JavaScript (not using JQuery)?
Or can i get array of div's by id that's starts with "c[numeric_value]"?
[numeric_value_can_consist_of_some_numbers]
It's the similar question like stackoverflow/questions/1225611/ (but i don't have reputation to ask in that question). Thanks in advance.
I have html, like this:
<div id="c0" class="bz_ment bz_first_ment"></div>
<div id="c1" class="bz_ment"></div>
<div id="c2" class="bz_ment"></div>
<div class="bz_add_ment"></div>
How can I get array of all the div's (3 div in example) by class that's starts with "bz_ment[anysymbols]" in JavaScript (not using JQuery)?
Or can i get array of div's by id that's starts with "c[numeric_value]"?
[numeric_value_can_consist_of_some_numbers]
It's the similar question like stackoverflow./questions/1225611/ (but i don't have reputation to ask in that question). Thanks in advance.
Share Improve this question edited Jan 30, 2014 at 10:50 dmgl asked Jan 29, 2014 at 20:19 dmgldmgl 2775 silver badges12 bronze badges 16- Why can't you use jQuery? – CoderDennis Commented Jan 29, 2014 at 20:21
- are you using jQuery? – hunter Commented Jan 29, 2014 at 20:21
- 2 Are you two serious about the jQuery..? – Sterling Archer Commented Jan 29, 2014 at 20:25
- 7 Two users with 5K rep on the site remending jQuery for something trivial that is a) as easy without jQuery and b) indicates a bigger much design problem. This is very saddening to see, makes me wish downvoting ments was possible. – Benjamin Gruenbaum Commented Jan 29, 2014 at 20:26
- 4 @blackbird- wele to SO! where asking for JS help often turns into the great jQuery debate! (go with Benjamins answer, it is correct). – rlemon Commented Jan 29, 2014 at 20:34
2 Answers
Reset to default 5You should use .querySelectorAll
var matching = document.querySelectorAll('[class*="bz_ment"]')
I see some worrying things in your code though:
- You have sequential numeric IDs, consider using an
Array
to represent sequential data instead. - You are selecting things by class name identifiers, if you must do this - use a
data-*
attribute instead. Better yet, store the elements in an array instead and have a direct reference to them.
You can write a function to process elements on the page that contain the class you're looking for:
function containsClass(matchClassName) {
var matches = new Array();
var elems = document.getElementsByTagName('div'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClassName + ' ') > -1) {
matches.push(elems[i]);
}
}
return matches;
}
now you can write
var matches = containsClass('bz_ment');