Finding all class names used in HTML/DOM

后端 未结 8 1683
耶瑟儿~
耶瑟儿~ 2021-01-02 22:05

How can I get a list of all class names used inside an HTML Snippet?

For example, the HTML Snippet below,

8条回答
  •  忘掉有多难
    2021-01-02 22:45

    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.

提交回复
热议问题