Get only styles declared in CSS for an element

3

I am trying to make a CSS converter for inline styles using only client-side technologies.

Searching even found something, in the case is library (jquery.inlineStyler) and this is implementation , but it does not answer me how I would like it, since it converts all properties of style of element to style inline (including the default of the browser), which is not what I would like.

What I would like was for the only CSS properties converted to% inline to be declared in CSS, not all the default of the browser for that element.

A simple example of the result you'd like:

p {
  color: green;
  background-color: #ccc;
}
p.p2 {
  color: blue;
  font-size: 15pt;
}
<p>Paragrafo</p>
<p class="p2">Paragrafo 2</p>

Where the expected result for this HTML would be:

<p style="color: green;background-color: #ccc;">Paragrafo</p>
<p style="color: blue;background-color: #ccc;font-size: 15pt;">Paragrafo 2</p>
    
asked by anonymous 08.06.2015 / 21:59

1 answer

3

As far as I know there is no simple way (native method or library) that does this. There is no native method for this it is difficult to do this with JavaScript because some rules overlap and it is difficult to know which one has priority.

But I started with an idea that you can continue if you want and be useful.

var estilos = document.styleSheets; // CSSStyleSheet.rules
for (var i = 0; i < estilos.length; i++) {
    var regras = estilos[i].rules;
    for (var j = 0; j < regras.length; j++) {
        var str = regras[j].cssText;
        var seletor = str.split('{')[0];
        var style = str.match(/\{([^\{\}]*)\}/)[1];
        aplicar(seletor, style);
    }
}

function aplicar(seletor, regras) {
    console.log(seletor, '-', regras);
    var elementos = document.querySelectorAll(seletor);
    for (var i = 0; i < elementos.length; i++) {
        var el = elementos[i];
        var regrasExistentes = el.getAttribute('style') || '';
        el.setAttribute('style', regrasExistentes + regras);
    }
}

jsFiddle: link

One step that is missing and what I do not have time to do is to check the inline styles already inserted and compare them with the next rule that will be applied to it. It seems that Browser solves this naturally since the styles are sorted from first to last but I have not had time to test ...

    
08.06.2015 / 22:25