0

I have a simple question - is it even possible to get element's HTML with styles from DOM? I don't need any jQuery object, just plain HTML with all styles.

I would use it in case were I have grid with different styles across rows and I would like to get that html and styles and sent it to server where I would use it in a mail body - programatically ofcourse.

Is there an elegant way to do that?

Tnx for answers

Sobis
  • 1,385
  • 4
  • 20
  • 29

1 Answers1

3

$.html() (with no arguments) does exactly this: http://api.jquery.com/html/

From the example on the page:

<p>

  <b>Click</b> to change the <span id="tag">html</span>
</p>
<script>
  $("p").click(function () {
    var htmlStr = $(this).html();
    $(this).text(htmlStr);
  });
</script>

When the function is called, the contents of htmlStr is

<b>Click</b> to change the <span id="tag">html</span>

(as a string)

Ben Parsons
  • 1,425
  • 1
  • 14
  • 30
  • Hmm maybe you missunderstood me. Take a look at http://jsfiddle.net/vzddd/5/ I want #result to be something like

    Lorem ipsum

    and not just Lorem ipsum
    – Sobis Aug 01 '12 at 11:54
  • So you want the styles from the CSS added to the inline elements? How would that even work - in that fiddle there is nothing for `color: red;` to be applied to. – Ben Parsons Aug 01 '12 at 11:55
  • Yes, I would like to get grid's view in just HTML - so if I get this html and I paste it in empty html file and open it - I get the same view as in original web page. – Sobis Aug 01 '12 at 11:57
  • HTML with all styles for elements in it. In this (jsfiddle.net/vzddd/5 ) case:

    Lorem ipsum

    – Sobis Aug 01 '12 at 12:03
  • Well you'll definitely need something custom for that. To get the "outerHtml" change your jsfiddle to `var htmlStr = $('.testClass').clone().wrap('

    ').parent().html();`, that will preserve all the classes and the parent element. To move the actual text of the CSS is a different question, but it's still doable.

    – Ben Parsons Aug 01 '12 at 12:09
  • 1
    Turns out that someone has done this already - see this link. http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element – Ben Parsons Aug 01 '12 at 12:40