jQuery - How to get all styles/css (defined within internal/external document) with HTML of an element


Tags: javascript,jquery,css,styles

Problem :

I know that $("#divId").html() will give me innerHtml. I also need its styles (which might be defined by the means of classes) either in-line style attribute or all the styles/classes within a separate <style> tag.

Is it possible?

UPDATE
What if html is like <div id="testDiv">cfwcvb</div> and a css class for #testDiv is defined in external stylesheet?

UPDATE 2
Sorry for not clarifying this earlier

If this is my HTML

<div id="divId">
    <span class="someClass">Some innerText</span>
</div>

And styles are defined in separate style sheet or in head styles.

#divId {
    clear: both;
    padding: 3px;
    border: 2px dotted #CCC;
    font-size: 107%;
    line-height: 130%;
    width: 660px;
}
.someClass {
    color: blue;
}

Then when I try to get inner html of $("#divId").html() or call any other custom function, I need something like below

<style>
#divId {
    clear: both;
    padding: 3px;
    border: 2px dotted #CCC;
    font-size: 107%;
    line-height: 130%;
    width: 660px;
}
.someClass {
    color: blue;
}
</style>

<div id="divId">
    <span class="someClass">Some innerText</span>
</div>

UPDATE 3 for Answer by kirilloid
I ran below code in Command Window of Chrome Debugger tools for this page itself and this is what I see TypeError: Cannot read property 'rules' of undefined

function getElementChildrenAndStyles(selector) {
  var html = $(selector).get(0).outerHTML;

  selector = selector.split(",").map(function(subselector){
    return subselector + "," + subselector + " *";
  }).join(",");
  elts = $(selector);

  var rulesUsed = [];
  // main part: walking through all declared style rules
  // and checking, whether it is applied to some element
  sheets = document.styleSheets;
  for(var c = 0; c < sheets.length; c++) {
    var rules = sheets[i].rules || sheets[i].cssRules;
    for(var r = 0; r < rules.length; r++) {
      var selectorText = rules[r].selectorText;
      var matchedElts = $(selectorText);
      for (var i = 0; i < elts.length; i++) {
        if (matchedElts.index(elts[i]) != -1) {
          rulesUsed.push(CSSrule); break;
        }
      }
    }
  }
  var style = rulesUsed.map(function(cssRule){
    if ($.browser.msie) {
      var cssText = cssRule.style.cssText.toLowerCase();
    } else {
      var cssText = cssRule.cssText;
    }
    // some beautifying of css
    return cssText.replace(/(\{|;)\s+/g, "\$1\n  ").replace(/\A\s+}/, "}");
    //                 set indent for css here ^ 
  }).join("\n");
  return "<style>\n" + style + "\n</style>\n\n" + html;
};
getElementChildrenAndStyles(".post-text:first");


Solution :

outerHTML (not sure, you need it — just in case)

Limitations: CSSOM is used and stylesheets should be from the same origin.

function getElementChildrenAndStyles(selector) {
  var html = $(selector).outerHTML();

  selector = selector.split(",").map(function(subselector){
    return subselector + "," + subselector + " *";
  }).join(",");
  elts = $(selector);

  var rulesUsed = [];
  // main part: walking through all declared style rules
  // and checking, whether it is applied to some element
  sheets = document.styleSheets;
  for(var c = 0; c < sheets.length; c++) {
    var rules = sheets[c].rules || sheets[c].cssRules;
    for(var r = 0; r < rules.length; r++) {
      var selectorText = rules[r].selectorText;
      var matchedElts = $(selectorText);
      for (var i = 0; i < elts.length; i++) {
        if (matchedElts.index(elts[i]) != -1) {
          rulesUsed.push(rules[r]); break;
        }
      }
    }
  }
  var style = rulesUsed.map(function(cssRule){
    if (cssRule.style) {
      var cssText = cssRule.style.cssText.toLowerCase();
    } else {
      var cssText = cssRule.cssText;
    }
    // some beautifying of css
    return cssText.replace(/(\{|;)\s+/g, "\$1\n  ").replace(/\A\s+}/, "}");
    //                 set indent for css here ^ 
  }).join("\n");
  return "<style>\n" + style + "\n</style>\n\n" + html;
}

usage:

getElementChildrenAndStyles("#divId");

    CSS Howto..

    ASP.NET MVC2 + CSS - how to refresh CSS?

    How to align arrows using CSS or jQuery or JavaScript [closed]

    Amazing CSS Div scrolling effect, cant explain, link provided. This is a web design issue, how to get an effect like this?

    How to pause a CSS keyframe animation when it ends the first cycle?

    Meteor how to serve multiple css for different media types?

    HTML/CSS- how to align part of a cell to the left, and part to the right?

    How to use global variables in CSS-Modules?

    How to select children in CSS

    How to vertical align the text inside a div in responsive layout

    Webpage Css Error.. Not Showing Anything

    How can I convert AI to HTML & CSS to use in ASP.Net Application

    Before CSS, how one would change margins and paddings?

    How to select by CSS styles in jQuery?

    how to make div with image like below in html and css

    How to hide a div with jquery or alternative?

    jQuery show multiple image thumbnail before upload

    How to use jQuery UI icons without buttons?

    How to make these imgs 2 rows, overflow the browser be seen with scroll right? not change to row 3

    How to get a background image to print using css?

    CSS flex, how to display one item on first line and two on the next line

    How to Move Parent Div Position using css on hover

    How to make my asp chart scrollable in the x direction

    CSS : How to make two column right fluid left fluid depend on right

    How to create a multiple columns with HTML CSS

    How can I use a CSS selector to match two classes being present?

    How can I force Internet Explorer to apply CSS styles

    How to use a backslash in css content property?

    How to display mouseover effect in GridView rows using only CSS?

    Wordpress: How to add a caption right-aligned to the edge of the image

    how to remove table border line?