Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 912
dmgl Avatar asked Feb 14 '23 22:02

dmgl


1 Answers

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.
like image 181
Benjamin Gruenbaum Avatar answered Feb 24 '23 18:02

Benjamin Gruenbaum