Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to convert finished html to html inline styled fragment #248

Open
rhwoodpecker opened this issue Jul 10, 2023 · 1 comment
Open

How to convert finished html to html inline styled fragment #248

rhwoodpecker opened this issue Jul 10, 2023 · 1 comment

Comments

@rhwoodpecker
Copy link

like:

  <html> 
     <style>p { width: 20px;} </style>
     <body>
        <p>hhhh</p>
     </body>
  </html>

got:
<p style="width: 20px">hhh</p>

@kinee1
Copy link

kinee1 commented Apr 29, 2024

To convert a finished HTML document with external CSS styles into an HTML fragment with inline styles applied directly to the elements, you'll need to:

Extract the CSS styles from the <style> tag and apply these styles directly to the corresponding HTML elements.
Here's a basic approach using JavaScript to achieve this:

let originalHTML = `
  <html> 
     <style>p { width: 20px;} </style>
     <body>
        <p>hhhh</p>
     </body>
  </html>
`;

// Parse the HTML string into a DOM object
let doc = new DOMParser().parseFromString(originalHTML, 'text/html');

// Extract and apply CSS styles inline
let styleTags = doc.querySelectorAll('style');
styleTags.forEach(styleTag => {
    let style = styleTag.textContent.trim();
    let elementsWithStyles = doc.querySelectorAll(styleTag.getAttribute('type') || 'style');
    elementsWithStyles.forEach(el => {
        el.removeAttribute('style'); // Remove existing inline styles
        el.setAttribute('style', style); // Apply inline styles from external CSS
    });
    styleTag.remove(); // Remove the <style> tag
});

// Convert the modified DOM back to an HTML string
let modifiedHTML = doc.documentElement.outerHTML;
console.log(modifiedHTML);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants