简体   繁体   中英

detecting class names un-used on html code

exist any way or tool to detecting class names un-used on html code.

i have some html code with old bootstrap; jquery and personalised css style like this:

<div class="clear fot-her likes tab-sub">content</div>

but i need purge un-used if fot-her class name not apply any style get add it to a list and show in and alert.

i find only this but i can get the class name:

var style = window.getComputedStyle(element [, pseudoElt]);

and this only get the element by class name given:

var elements = document.getElementsByClassName(names);

script

function checkClassCSS() {
    let doc = document.all;
    let style = document.styleSheets;
    var listofClases = []
    Object.entries(doc).forEach(([key, element]) => {
        let classes = element.className.split(/\s+/);
        let new_classes = []
        classes.forEach((cl) => {
            if (cl != '') {
                new_classes = new_classes.concat(['.' + cl]);
            }
        });
        listofClases = listofClases.concat(new_classes);
    });
    listofClases = listofClases.filter(v => v != '');
    listofClases = Array.from(new Set(listofClases));
    var SelectorClass = []
    Object.entries(style).forEach(([key, node]) => {
        let rule = node.cssRules;
        Object.entries(rule).forEach(([key, cssSelector]) => {
            SelectorClass = SelectorClass.concat([cssSelector.selectorText]);
        });
    });
    SelectorClass = SelectorClass.filter(v => v != '');
    SelectorClass = Array.from(new Set(SelectorClass));
    var missing = [];
    listofClases.filter(function(x) {
        if (!SelectorClass.includes(x)) {
            missing.push(x);
        }
    })
    console.log(missing);
}

I can't get the unused class names correctly for example: col-lg-4 may be used in html code but it still appears in missing variable.

Get document.all and look for tagName=="STYLE" .
In all of those (if any), look for sheet.cssRules and for each, selectorText .
These are supposed to be the classes - collect the into an array.
Then, go through all the other document.all , look for classList .
Compare them to array - if found in array, good, if not: alert.
Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM