を、 category-
の場合は、一致するクラスを含むすべての要素を最初に取得する必要があります。attribute contains selector:
document.querySelectorAll("*[class*='category-']")
これらの要素のすべてのクラスを抽出し、重複しているものと、目的の接頭辞で始まらないものを除外する必要があります。
このような何か:
const allCategoryClasses = [];
// Get all elements that have any class starting
// with 'category-':
const elementsWithCategoryClasses
= document.querySelectorAll("*[class*='category-']");
const elementsCount = elementsWithCategoryClasses.length;
for (let i = 0; i < elementsCount; ++i) {
// Append all the classes of the matching elements to
// allCategoryClasses.
// Note we are not filtering out the other classes that
// do not start with 'category-' yet.
Array.prototype.push.apply(
allCategoryClasses,
elementsWithCategoryClasses[i].classList
);
}
// Now filter out the classes that do not start with
// 'category-' here, so we do it just one time, instead
// of doing it once for each single element.
// Also, use and object to remove duplicates.
const presentClasses = {};
console.log(allCategoryClasses
.filter((classname) => {
const present = presentClasses[classname];
presentClasses[classname] = true;
return classname.indexOf("category-") === 0 && !present;
}));
// This will also filter out duplicates:
// const presentClasses = {};
// allCategoryClasses
// .forEach((classname) => {
// if (classname.indexOf("category-") === 0) {
// presentClasses[classname] = true;
// }
// });
// console.log(Object.keys(presentClasses));
<div class="category-a other-class"></div>
<div class="other-class category-b"></div>
<div class="category-c category-d other-class"></div>
<div class="category-e other-class category-f"></div>
<div class="other-class"></div>
<div class="category-e other-class category-f"></div>
の可能性のある重複した[?jqueryのすべてのクラス要素を選択する方法は、 "テキストベース" で始まる](https://stackoverflow.com/questions/4161869/jquery-how-to-select-all-the-class-elements-start-with-text) – Liam
@Javid誰かがあなたの問題を解決しましたか?もしそうなら、あなたは最高の答えを受け入れてください(ポイントの下にあるチェックマークをクリックしてください)。それはあなたの質問に出くわす他のユーザーがすぐに受け入れられた答えを見つけるのを助け、15人の担当者も与えます。 ( – Danziger