An admission: what follows may not be the ideal solution in my view. I felt compelled to include it as there may be situations where resorting to unconventional methods is unavoidable, rather than modifying the CSS files.
In general, as Quentin and Bryant have pointed out, there is no inherent "namespacing" for CSS files. Consequently, loading all CSS files can result in the classes from the last file taking precedence (even when conflicting with other names) and making it challenging to differentiate between them.
If, by some chance, you are unconcerned about Chrome users, you might potentially utilize the cssRules
or rules
properties of the document.styleSheets[i]
object for each loaded stylesheet file (i
representing the file number). However, it should be noted that this approach does not function in Chrome according to this source. For some reason, both cssRules
and rules
are null in Chrome for each styleSheets[i]
.
A potential workaround:
- Once all necessary CSS files are loaded,
- Within your JavaScript code, read the chosen CSS file as if it were a text file. AJAX can be used for this purpose - refer to this discussion for guidance.
Search for the specific selector within the retrieved text and extract that portion. You could potentially parse the entire file to extract the relevant content.
During my investigation on how to accomplish this step, I encountered the document.styleSheets[i].cssRules
object alongside the ineffective method in Chrome.
- Create a style element incorporating the extracted content and append this style element to the head element (an example illustrating how to create and append style elements to the head element).
While this approach may seem suboptimal for various reasons (e.g., performance, elegance, readability) and likely indicates that the design of the CSS files needs reassessment for the project (consider Bryant's recommendations), I deemed it important to present this answer. There is a method available, albeit a somewhat makeshift one, for cases where altering the CSS files is not feasible and utilizing them unchanged is a necessity.