1

I am dynamically generating elements:

<a class="gallery1" href="base64String"> 
    <img src="base64StringThumbnail">
</a>

where numerical value suffix to gallery changes, I can't predict the numerical value ahead of time, so the regex for the class would be "gallery\\d+". I'd like get just all the classes without duplicates that match that regex

So I could write something like that:

$(document).ready(function () {
  for(const clazz in matchedClasses){
    $('.' + clazz).createGallery();
  }
});

For instance if I have elements with classes: gallery1, gallery2, gallery1, gallery3, gallery2 in DOM, I would get: [gallery1, gallery2, gallery3] in any order. that's easy for me in C# and Java, but I don't know how to achieve that in JS.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Yoda
  • 17,363
  • 67
  • 204
  • 344

2 Answers2

1

You can target all the elements with querySelectorAll() and attribute starts with selector. Then loop through them to get the class from the elements with .map(). Finally remove the duplicates using Spread syntax and Set.

Try the following way:

var galleryList = document.querySelectorAll('[class^="gallery"]');
var res = [...new Set(Array.from(galleryList).map(g => g.getAttribute('class')))];
console.log(res);
<a class="gallery1" href="base64String"> 
  <img src="base64StringThumbnail">
</a>
<a class="gallery2" href="base64String"> 
  <img src="base64StringThumbnail">
</a>
<a class="gallery3" href="base64String"> 
  <img src="base64StringThumbnail">
</a>
<a class="gallery1" href="base64String"> 
  <img src="base64StringThumbnail">
</a>
<a class="gallery2" href="base64String"> 
  <img src="base64StringThumbnail">
</a>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Let consider you can the following code which is all the classes as you said into a variable.

let allClasses = ['gallery1', 'gallery2', 'gallery1', 'gallery3', 'gallery2'];

Now to get only ['gallery1', 'gallery2', 'gallery3'] now do like this

let allClasses = ['gallery1', 'gallery2', 'gallery1', 'gallery3', 'gallery2'];

let resultClasses = Array.from(new Set(allClasses));

console.log(resultClasses); // ['gallery1', 'gallery2', 'gallery3']

Because the Set data structure guarantee the uniqueness of its values

Patrissol Kenfack
  • 764
  • 1
  • 8
  • 22