3

I am working on a bookmarklet project. So when user clicks on bookmarklet he can grab partial part of a web page and view it somewhere else.

The problem is that partial element (lets assume div) has css styles and classes applied.

Is there any way to loop through all child elements of selected div and convert class properties to style properties so I can keep formatting?

For example below a sample screenshot; I need to take out all applied classes and convert them into style attributes in selected area.

enter image description here

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158

2 Answers2

6
(function($) {
    $.extend($.fn, {
        makeCssInline: function() {
            this.each(function(idx, el) {
                var style = el.style;
                var properties = [];
                for(var property in style) { 
                    if($(this).css(property)) {
                        properties.push(property + ':' + $(this).css(property));
                    }
                }
                this.style.cssText = properties.join(';');
                $(this).children().makeCssInline();
            });
        }
    });
}(jQuery));

You would call it using

$(".select").makeCSSInline();

The problem with this function is that it brings every CSS property into the tag, so it can cause a major performance hit, but if you are willing to take that risk, go ahead

Fiddle

Function acquired from here

Community
  • 1
  • 1
Cody Guldner
  • 2,888
  • 1
  • 25
  • 36
  • Very good solution, nasty but gets the job done. As implied in your statement, this should be a last resort and comes with the "Surgeon Generals Warning": `Your users may experience lag, performance, or health concerns with repeated use of this solution` – GoldBishop Mar 28 '17 at 17:03
0

Fixed to use with bootstrap

(function($) {
    $.extend($.fn, {
        makeCssInline: : function(sizes) {
            this.each(function(idx, el) {
                var style = el.style;
                var properties = [];
                for(var property in style) {
                    if(property=="height" || property=="width") { continue; }
                    if($(this).css(property)) {
                        properties.push(property + ':' + $(this).css(property));
                    }
                }

                if(sizes) {
                    properties.push("width" + ':' + $(this).width()+"px");
                    properties.push("height" + ':' + $(this).height()+"px");
                }

                this.style.cssText = properties.join(';');
                $(this).children().makeCssInline();
            });
        }
    });
}(jQuery));