Posted 14 September 2023, 4:54 am EST
Hi Ricardo,
Currently, SpreadJS doesn’t have a flag/method to convert the inline styles to the classes. However, you could create your own custom function to separate out the inline css from the html.
Kindly refer to the following code snippet and the sample:
function convertInlineStylesToClasses(htmlContent) {
// Create a dummy element to parse the HTML content
const dummyElement = document.createElement('div');
dummyElement.innerHTML = htmlContent;
// Initialize a styleMap object to store unique styles and their corresponding class names
const styleMap = new Map();
// Generate a unique class name for a style
function generateClassName(style) {
return `style-${styleMap.size + 1}`;
}
// Traverse all elements and extract inline styles
function traverse(element) {
if (element.nodeType === Node.ELEMENT_NODE) {
const styleAttribute = element.getAttribute('style');
if (styleAttribute) {
if (!styleMap.has(styleAttribute)) {
const className = generateClassName(styleAttribute);
styleMap.set(styleAttribute, className);
}
const className = styleMap.get(styleAttribute);
element.classList.add(className);
element.removeAttribute('style');
}
for (const childElement of element.childNodes) {
traverse(childElement);
}
}
}
// Start traversing from the root element
traverse(dummyElement);
// Generate the <style> tag content
let styleTagContent = '<style>';
for (const [style, className] of styleMap) {
styleTagContent += `.${className} {${style}}`;
}
styleTagContent += '</style>';
// Combine the <style> tag and modified HTML content
const finalHTML = styleTagContent + dummyElement.innerHTML;
return finalHTML;
}
Sample: https://jscodemine.grapecity.com/share/7WBE8EhUjECFCcqxt9jB8A/?defaultOpen={"OpenedFileName"%3A["%2Findex.html"%2C"%2Fapp.js"]%2C"ActiveFile"%3A"%2Fapp.js"}
With this code snippet, you could achieve your expected behavior mentioned above. Please let us know if you face any issues.
Yes, you could post the issues related to SpreadJS on the dedicated SpreadJS forum at: https://www.grapecity.com/forums/spreadjs
Regards,
Ankit