dmgl
dmgl

Reputation: 277

JS. How to get list of div's with similar class name?

I have html, like this:

<div id="c0" class="bz_comment bz_first_comment"></div>
<div id="c1" class="bz_comment"></div>
<div id="c2" class="bz_comment"></div>
<div class="bz_add_comment"></div>

How can I get array of all the div's (3 div in example) by class that's starts with "bz_comment[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.com/questions/1225611/ (but i don't have reputation to ask in that question). Thanks in advance.

Upvotes: 4

Views: 3025

Answers (2)

hunter
hunter

Reputation: 63562

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_comment');

Upvotes: 3

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

You should use .querySelectorAll

var matching = document.querySelectorAll('[class*="bz_comment"]')

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.

Upvotes: 5

Related Questions