-4

I want to get all html in a div with the css. Most of the css is in classes in an external css file.

  document.getElementById("mydiv")

this only gives me the html with the inline css. Is it even possible to somehow render the page with the css as inline even though it comes from css-files?

Daniel Gustafsson
  • 1,725
  • 7
  • 37
  • 78

3 Answers3

1

How about using this function here, sourced from this answer:

function css(a) {
    var sheets = document.styleSheets, o = {};
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.is(rules[r].selectorText)) {
                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return o;
}

function css2json(css) {
    var s = {};
    if (!css) return s;
    if (css instanceof CSSStyleDeclaration) {
        for (var i in css) {
            if ((css[i]).toLowerCase) {
                s[(css[i]).toLowerCase()] = (css[css[i]]);
            }
        }
    } else if (typeof css == "string") {
        css = css.split("; ");
        for (var i in css) {
            var l = css[i].split(": ");
            s[l[0].toLowerCase()] = (l[1]);
        }
    }
    return s;
}

As a use case:

var style = css($("#myDiv")); // Retrieve all styles from $("#myDiv")
$("#elementToPutStyleInto").css(style); // Put those styles onto another element.

Then, to get each element within the <div>:

// .find('*') gets every child element.
$('#myDiv').find('*').each(function() {
    // Do stuff here to each element using `this`
    console.log(this);
});

Combine the two to get the information you need.

Community
  • 1
  • 1
Nick Bull
  • 9,518
  • 6
  • 36
  • 58
0

If you want to get another html document in a div Use iframe

<iframe src="one.htm" height="200" width="300"></iframe>
Head In Cloud
  • 2,001
  • 1
  • 8
  • 10
  • what do you mean by get another html document? I just want the html code as a string with css so i can pass it down to my c# controller – Daniel Gustafsson Aug 03 '16 at 08:47
0

Here is a possible solution from the MDN here is the article https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

and here the code.

  function getTheStyle(){
    var elem = document.getElementById("elem-container");
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = theCSSprop;
   }
  getTheStyle();
 #elem-container{
   position: absolute;
   left:     100px;
   top:      200px;
   height:   100px;
 }
<div id="elem-container">dummy</div>
<div id="output"></div>  

With this you could iterate through all elements and Properties. It is not the whole code you might need, but a good starting point.

winner_joiner
  • 12,173
  • 4
  • 36
  • 61