Finding all class names used in HTML/DOM

后端 未结 8 1654
耶瑟儿~
耶瑟儿~ 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:39

    I'd do something like the snippet below, it uses jQuery but that's just easier to read imo, a Javascript version wouldn't be much harder I'd assume.

    Basically you want to get all of the nodes, then add all of the unique classes to a list..

    This is much harder to implement if you're looking for dynamic classes which may be applied with Javascript.

    Nesting would require more insight as to how it should be performed, how to handle dupe classes but not dupe class arrays and similar..

    If this get's downvoted because of the jQuery I'll be upset.

    var classes = [];
    
    $('body *:not(script)').each(function(){
      _classes = $(this).attr('class') ? $(this).attr('class').split(' ') : []
      _classes.forEach(function(entry){
        if(classes.indexOf(entry) < 0){
          classes.push(entry)
        }
      })
    })
    
    console.log(classes)
    
    

提交回复
热议问题