How can I get a list of all class names used inside an HTML Snippet?
For example, the HTML Snippet below,
<div class="name">
<div class="first"></div>
<div class="last"></div>
</div>
would have output name
, first
, last
or name
, name > first
, name > last
. Here, I am concerned about finding all class selectors first. Nesting could be optional.
I expect to use Javascript or Regular Expressions.
Open the page in a browser, like Chrome or Firefox, right click and inspect the element, You should see the source, there you can see the class.
getElementsByClassName() The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
Piggybacking off of the one-liner from @user1679669 and @Nermin's answer using Set, you can get a list of all the classes on a page with this one-liner:
const allClasses = [...new Set([].concat(...[...document.querySelectorAll('*')].map(elt => [...elt.classList])))];
const allClasses = Array.from(document.querySelectorAll('[class]')).flatMap(e => e.className.toString().split(/\s+/))
const classes = new Set()
allClasses.forEach(c => classes.add(c))
console.log(classes)
Get all the class names and split on space so for example, "child first" would become 'child' and 'first'. If you don't like this behaviour you can remove the toString and split functions.
Then add every class name to the set. There is no need to check for duplicates since the set does that for us. If you do want to store duplicates you can use a Map instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With