santa
santa

Reputation: 12512

Strip CSS class names and put in an array

I have ah HTML file. CSS is at the beginning of the document, within tags. I need to get the class names of those classes that are located between comment tags

/* target >> */
.oneClass { ... }
.anotherOne { ... }    
/* target << */ 

I need to put the class names into an array

var myArray = new Array("oneClass","anotherOne " ...);

I can not really use anything server side scripting and is pretty much limited to basic JS. I assume I need some sort of regex, but this is way outside of my competency. Need some help.

Upvotes: 0

Views: 70

Answers (1)

joseeight
joseeight

Reputation: 924

Maybe this will work, better than Regex since you won't be parsing the string, and get the actual rules interpreted by the browser.

var targetStyles = ((document.getElementsByTagName('style')[0].innerText).split('/* target >> */')[1]).split('/* target << */')[0];

var dimp = window.document.implementation.createHTMLDocument('');
var styleEl = dimp.createElement('style');
styleEl.innerHTML = targetStyles;
dimp.head.appendChild(styleEl);

var myArray = [], i, length = styleEl.sheet.rules.length;

for (i=0; i<length; i++) {
    myArray.push(styleEl.sheet.rules[i].selectorText);
}

//myArray contains what you are looking for.

JSFiddle with working demo.

Upvotes: 1

Related Questions