It seems like you're on the right track with your solution, but there are a few tweaks needed to make it work properly. Instead of pushing an array into the getClasses
function, you should be passing individual classes. Remember that neither strings nor arrays have a standard contains
method; you may want to use includes
instead.
let classesWithDashes = new Set();
document.querySelectorAll('*').forEach(element => {
for (const cls of element.className.split(' ').filter(name => name.includes("-"))) {
classesWithDashes.add(cls);
}
});
// Now, `classesWithDashes` contains all the class names with dashes
// If you need them in an array format:
classesWithDashes = [...classesWithDashes];
Here's a demonstration:
let classesWithDashes = new Set();
document.querySelectorAll('*').forEach(element => {
for (const cls of element.className.split(' ').filter(name => name.includes("-"))) {
classesWithDashes.add(cls);
}
});
// `classesWithDashes` now holds the classes with dashes
// Convert to an array if needed:
classesWithDashes = [...classesWithDashes];
console.log(classesWithDashes);
<div class="foo foo-bar"></div>
<div class="another-one"></div>
<div class="no-dash-class"></div>
(I've always wondered why Set
doesn't include something like an addAll
method or allow multiple values to be passed to add
, similar to push
...)