JS. How to get a list of divs with a 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 an array of all divs (3 divs in the example) by class that starts with "bz_comment [anysymbols]" in JavaScript (without using jQuery)?

Or can I get a div array by id that starts with "c [numeric_value]"?

[numeric_value_can_consist_of_some_numbers]

This is a similar question, for example stackoverflow.com/questions/1225611/(but I have no reputation to ask in this question). Thanks in advance.

+4
source share
2 answers

You have to use .querySelectorAll

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

I see some troubling things in your code:

+5

, , :

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;
}

var matches = containsClass('bz_comment');
+3

Source: https://habr.com/ru/post/1524366/


All Articles