Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
  ").replace(/As+}/, "}");
    //                 set indent for css here ^ 
  }).join("
");
  return "<style>
" + style + "
</style>

" + html;
}

usage:

getElementChildrenAndStyles("#divId");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...