4

I undertand that the following jquery code captures all html text content within the said <div> class:

$("div.content").html();

However what I would like to do is also to capture the formatting, like the table border and it's background color. How do I do that since html() is only capturing the text and its formatting?

Hope someone can advise. Thanks.

George
  • 34,712
  • 7
  • 55
  • 91
John Java
  • 143
  • 1
  • 2
  • 7
  • **[.css()](http://api.jquery.com/css/)** + **[.children()](http://api.jquery.com/children/)** + **[.each()](http://api.jquery.com/each/)** – Patsy Issa Nov 29 '13 at 08:19
  • 7
    You mean you want to also fetch the styling defined in parent elements or in external css files ? So you probably want [getComputedStyle](https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle). – Denys Séguret Nov 29 '13 at 08:19
  • `html()` basically returns the HTML as received by the browser. Most styling is usually done in stylesheets though. – Felix Kling Nov 29 '13 at 08:22
  • 1
    What your asking for is a string representation of the current state of the selected element that contains all of the applicable CSS rules applied inline. This is theoretically possible, however, to my knowledge, no solution exists and it would take tremendous work to make a fully functional implementation. This is far outside the scope of a simple StackOverflow question. Perhaps you could explain why you need this so that we can guide you in the direction in which you truly need to go. – Tyler Crompton Nov 29 '13 at 08:23
  • Your precise question/use case isn't clear. What's the exact purpose ? Take a kind of snapshot ? Don't forget that the rendering usually changes with container dimensions for example. – Denys Séguret Nov 29 '13 at 08:25
  • yes,there is some cnfusion..what exactly do you want..? – HIRA THAKUR Nov 29 '13 at 08:26
  • Hi On a serious note and dystroy, I am basically trying to allow the user to print the page. The content is already there in the .jsp, so my intention is to print out the necessary. – John Java Dec 02 '13 at 05:49

2 Answers2

1

jQuery's .css method returns computed style as well, and is better because it accounts for browser difference.

Specify style properties you want to get and store:

var color = $( "div.content" ).css( "background-color" );
var position = $( "div.content" ).css( "position" );
var overflow = $( "div.content" ).css( "overflow" );

Use them later:

$('div.contentUpdated').css('color', color).css('position', position).css('overflow', overflow);

jsFiddle Example

EDIT 1:

You could also loop through objects' style properties by writing a custom* jQuery plug-in:

$.fn.getStyleObject = function(){
    var dom = this.get(0);
    var style;
    var returns = {};
    if(window.getComputedStyle){
        var camelize = function(a,b){
            return b.toUpperCase();
        }
        style = window.getComputedStyle(dom, null);
        for(var i = 0, l = style.length; i < l; i++){
            var prop = style[i];
            var camel = prop.replace(/\-([a-z])/, camelize);
            var val = style.getPropertyValue(prop);
            returns[camel] = val;
        }
        return returns;
    }
    if(dom.currentStyle){
        style = dom.currentStyle;
        for(var prop in style){
            returns[prop] = style[prop];
        }
        return returns;
    }
    if(style = dom.style){
        for(var prop in style){
            if(typeof style[prop] != 'function'){
                returns[prop] = style[prop];
            }
        }
        return returns;
    }
    return returns;
}
 

jsFiddle Example

EDIT 2:

I have written for you a simple example of how to get one object's content and style, and later impose it on the new object. I simply used jQuery and its .each() iterator function:

$(function () {
    var width = $("#div").css("width");
    var height = $("#div").css("height");
    var backgroundColor = $("#div").css("background-color");
    var color = $("#div").css("color");
    var font_weight = $("#div").css("font-weight");
    var font_size = $("#div").css("font-size");
    var content = $("#div").html();
    
    // Append the original content
    $("#updatedDiv").append(content);
    
    //
    // Store CSS properties in an array
    var cssProperties = {
        'width': width,
        'height': height,
        'background-color': backgroundColor,
        'color': color,
        'font-weight': font_weight,
        'font-size': font_size
    };
    
    //
    // Set CSS properties on the new object
    $.each(cssProperties, function(key, value) {
      $("#updatedDiv").css(key, value);
    });
});

jsFiddle Example

Community
  • 1
  • 1
Ilia Rostovtsev
  • 12,128
  • 10
  • 47
  • 80
  • Hi llia, thanks for the response. Going by your first example, since it seems like .css will not capture the html content, is there a way to use both .css() and .html()? I did the following: var color = $( "div.printarea" ).css( "background-color"); var text = $("div.printarea").html(); myWindow.document.write(text,color); The text value is displayed fine, however I get the value 'transparent' for color..:( Is there a way to combine .css() and .html()? – John Java Dec 01 '13 at 15:28
  • Yes but you shouldn't use `document.write`. Please take a look at my updated answer and `EDIT 2`. Example: http://jsfiddle.net/DGv2s/ – Ilia Rostovtsev Dec 01 '13 at 16:41
  • Hi llia, is the line: $("#updatedDiv").css(key, value); printing the text and the formatting to the screen? – John Java Dec 02 '13 at 05:57
  • No, John, this part `$("#updatedDiv").append(content);` will append old content, which is `Test` into the new object `
    `, which as you can see empty on my example. This part `$("#updatedDiv").css(key, value);` will be used to go through each *key/value* on the array `cssProperties`. `.each()` is iteration function, meaning that for each entry *(key/value)* from the array it will perform, first `$("#updatedDiv").css('width', width);`, then `$("#updatedDiv").css('height', height);`, and so on. Got it? P.S. Accept my answer if it's useful to you!
    – Ilia Rostovtsev Dec 02 '13 at 07:26
  • Hi llia, Thanks for the response, I am looking through the code and trying to fit it into my application. By the way, why do you say I should not use document.write? Cos in my app, this thing is supposed to be part of a popup page, as if they are printing a reciept kind of thing. – John Java Dec 02 '13 at 10:02
  • If you already using jQuery, my preference is to use `.append()`. Read more here: http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Ilia Rostovtsev Dec 02 '13 at 10:32
  • .append() seems to be adding content to an area pre-defined by div tags. How am I to do that in a pop up window?? – John Java Dec 02 '13 at 10:58
  • What kind of popup window? Does it use iframes? – Ilia Rostovtsev Dec 02 '13 at 11:20
1

You can use this function to get all styles, inline, computed etc.

Edit like you want it, it works. Check this jsfiddle: http://jsfiddle.net/65adr/40/

$.fn.copyCSS = function (source) {
        var dom = $(source).get(0);
        var dest = {};
        var style, prop;
        if (window.getComputedStyle) {
            var camelize = function (a, b) {
                    return b.toUpperCase();
            };
            if (style = window.getComputedStyle(dom, null)) {
                var camel, val;
                if (style.length) {
                    for (var i = 0, l = style.length; i < l; i++) {
                        prop = style[i];
                        camel = prop.replace(/\-([a-z])/, camelize);
                        val = style.getPropertyValue(prop);
                        dest[camel] = val;
                    }
                } else {
                    for (prop in style) {
                        camel = prop.replace(/\-([a-z])/, camelize);
                        val = style.getPropertyValue(prop) || style[prop];
                        dest[camel] = val;
                    }
                }
                return this.css(dest);
            }
        }
        if (style = dom.currentStyle) {
            for (prop in style) {
                dest[prop] = style[prop];
            }
            return this.css(dest);
        }
        if (style = dom.style) {
            for (prop in style) {
                if (typeof style[prop] != 'function') {
                    dest[prop] = style[prop];
                }
            }
        }
        return this.css(dest);
    };
Alessandro Incarnati
  • 6,288
  • 3
  • 32
  • 52