Reputation: 23
Parse the HTML Content You'll need to parse the HTML content, extract the inline styles, and create CSS classes for them. This can be done using the DOMParser in the browser environment.
Extract Inline Styles and Create CSS Classes Here’s how you can approach this: code for same code for remove style remove style dynamically
processInlineStyles(html: string): { html: string, styles: string } {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const elements = doc.body.querySelectorAll('*[style]');
let styleRules = '';
let classCounter = 0;
elements.forEach((element) => {
classCounter++;
const style = element.getAttribute('style');
const className = `custom-class-${classCounter}`;
// Add the new class to the element
element.classList.add(className);
element.removeAttribute('style');
// Create the CSS rule
styleRules += `.${className} { ${style} }\n`;
});
// Create a <style> element
const styleElement = doc.createElement('style');
styleElement.innerHTML = styleRules;
// Add nonce attribute if it exists on window
if (window['nonce']) {
styleElement.setAttribute('nonce', window['nonce']);
}
// Append the style element to the <head> of the parsed HTML
if (doc.head) {
doc.head.appendChild(styleElement);
} else {
// If <head> is not present, create it
const headElement = doc.createElement('head');
headElement.appendChild(styleElement);
doc.documentElement.insertBefore(headElement, doc.body);
}
return { html: doc.documentElement.outerHTML, styles: styleRules };
}
processInlineStyles(html: string): { html: string } {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const elements = doc.body.querySelectorAll('*[style]');
let styleRules = '';
let classCounter = 0;
elements.forEach((element) => {
classCounter++;
const style = element.getAttribute('style');
const className = `custom-class-${classCounter}`;
// Add the new class to the element
element.classList.add(className);
element.removeAttribute('style');
// Create the CSS rule
styleRules += `.${className} { ${style} }\n`;
});
// Check for existing <style> tag in the <head>
let styleElement = doc.head.querySelector('style');
if (!styleElement) {
// If no <style> tag exists, create one
styleElement = doc.createElement('style');
doc.head.appendChild(styleElement);
}
// Append the generated styles to the existing <style> tag
styleElement.innerHTML += `\n${styleRules}`;
// Add nonce attribute if it exists on window
if (window['nonce']) {
styleElement.setAttribute('nonce', window['nonce']);
}
// Return the modified HTML as a string
return { html: doc.documentElement.outerHTML };
}
Upvotes: 0
Views: 81