Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all class names used in HTML/DOM

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.

like image 547
Bimal Poudel Avatar asked Jun 25 '16 03:06

Bimal Poudel


People also ask

How do I find classes in HTML?

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.

What is used to find all HTML elements with the same class name?

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.

How do you select all classes in HTML?

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 (.)


2 Answers

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])))];

like image 71
hmnz Avatar answered Oct 29 '22 16:10

hmnz


Simple ES10 new Set() approach

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.

like image 30
Nermin Avatar answered Oct 29 '22 17:10

Nermin