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
").replace(/As+}/, "}");
// set indent for css here ^
}).join("
");
return "<style>
" + style + "
</style>
" + html;
};
getElementChildrenAndStyles(".post-text:first");
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…