Joynal Abedin
Joynal Abedin

Reputation: 21

How to get all class name at once form a HTML file to a CSS file

I have an HTML file and its mockup. Pulling the class name from the HTML file to the CSS file is pain full process. is there any way to get all the class names in a CSS file at once?

Upvotes: 1

Views: 950

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92677

Try this

function extract(html) {
  let m= html.match(/class=(".*?"|'.*?')/g)||[];            // class list
  let c= m.map(c=>c.replace(/class=("|')/,'').slice(0,-1)); // only names
  let dedup= [...new Set(c.map(x=>x.split` `).flat())];     // del duplicates

  return dedup.reduce((a,c) => a+=`.${c} {\n}\n\n`, '')
}
<textarea id="inp" cols="70" rows="4" placeholder="Paste html"></textarea>
<br><button onclick="output.value=extract(inp.value)">Extract CSS!</button>
<br><br><textarea id="output" cols="70" rows="4"></textarea>

Upvotes: 1

Aditya Aggarwal
Aditya Aggarwal

Reputation: 11

Maybe work in an advanced code editor like VS code which will make it easier for you to import class names with the help of autocomplete feature.

Upvotes: 1

Tohirul Islam
Tohirul Islam

Reputation: 404

I think there is an extension for this it is called evondev.

Here is my snippet that might work :

var html = "bla<p class='c1 c2'>blabla<button></button><div id='bla' class='c1 c3'></div>";

var classes = []; // empty array

html.replace(/class=['"][^'"]+/g, function(m){ // https://regex101.com/r/jD0wX1/1
    classes = classes.concat(m.match(/[^'"]+$/)[0].split(' ')); // https://regex101.com/r/jD0wX1/2
}); // take all classes

classes = classes.filter(function(item, pos) {
    return classes.indexOf(item) == pos;
}); // return unique classes

console.log(classes); // Run code snippet -> then press f12 to see the array

Try and Implement it. Feel free to ask for help in the comments

Upvotes: 1

Related Questions