0

I need to convert innline css to exsternal css, does anyone have an idea how? How to separate html and css and insert them into div-html and div-css.

For example:

From this:

<div id="one" style="background-color:green;width:50px;height:50px;">Div one</div>

to this:

<div id="one">Div one</div>
#one{
    background-color:green;
    width:50px;
    height:50px;
}

This is how it would look:

<div id="container"
    <div id="one" style="background-color:green;width:50px;height:50px;">Div one</div>
    <div id="two" style="background-color:red;width:150px;height:150px;">
          <div id="three" style="background-color:blue;width:50px;height:50px;">Div three</div>
    </div>
</div>

<div id="html"></div>
<div id="css"></div>
<button onclick="myFunction()" >click</button>
<script>
function myFunction(){
    var x = document.getElementById("container").innerHTML
    var html =
    var css =

    document.getElementById("html").innerHTML = html;
    document.getElementById("css").innerHTML = css;
}
</script>

1 Answer 1

2

Maybe something like this?

let style = '';

function myFunction() {
  document.querySelectorAll('div').forEach(e => {
    if (e.getAttribute('style')) {
      style += `
    #${e.getAttribute('id')}{${formatStyle(e.getAttribute('style'))}
    }`;
      e.removeAttribute('style');
    }
  });
  document.querySelector('#css').innerHTML = style;
  createStyleTag(style);
}

function formatStyle(style) {
  let tmp = '';
  let styles = style.split(';');
  styles.forEach(e => {
    if (e)
      tmp += `
       ${e};`;
  })
  return tmp;
}

function createStyleTag(css) {
  var head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

  head.appendChild(style);

  style.type = 'text/css';
  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
}
#css {
  white-space: pre;
}
<div id="container">
  <div id="one" style="background-color:green;width:50px;height:50px;">Div one</div>
  <div id="two" style="background-color:red;width:150px;height:150px;">
    <div id="three" style="background-color:blue;width:50px;height:50px;">Div three</div>
  </div>
</div>

<div id="html"></div>
<div id="css"></div>
<button onclick="myFunction()">click</button>

Sign up to request clarification or add additional context in comments.

2 Comments

what do you mean? its in JS.
I need to keep html visible (not to delete inlinecss from the existing one). Converted html and css just insert it into div-html (html part) and div-css (css part) so I can display and send it with ajax to exsternal css. No jQuery!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.