Skip to content

Instantly share code, notes, and snippets.

@perryraskin
Last active July 10, 2024 14:01
Show Gist options
  • Select an option

  • Save perryraskin/cccd9cb8ce882b0e3bddc63dfac23e10 to your computer and use it in GitHub Desktop.

Select an option

Save perryraskin/cccd9cb8ce882b0e3bddc63dfac23e10 to your computer and use it in GitHub Desktop.
Extract CSS classes out of HTML code
/*
* Use this script to extract CSS classes out of HTML code.
* Replace the test HTML code on line 8-9 with your HTML code.
* Run `node html-classes-to-css.js` in your terminal and a CSS file will be generated.
*/
const fs = require("fs");
var html =
`<div id="1432" class="test class-test another-class"><p class="bold text-small something"></p></div>`;
extractClasses(html);
function extractClasses(html) {
var classNameSet = new Set();
var classesIndex = html.indexOf('class="');
while (classesIndex > -1) {
var classesStartIndex = classesIndex + 7;
html = html.substring(classesStartIndex);
var classesEndIndex = html.indexOf('"');
var currentClassNames = html.substring(0, classesEndIndex).split(" ");
//console.log(html.substring(0, classesEndIndex));
currentClassNames.forEach((className) => {
classNameSet.add(className);
});
classesIndex = html.indexOf('class="');
}
console.log(classNameSet);
var classArray = Array.from(classNameSet);
var template = "";
classArray.forEach((className) => {
template += `.${className} { }\n\n`;
});
fs.writeFile("template.css", template, (error) => {
if (error) {
console.error(error);
return;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment