I'm writing a script that finds elements on a page that are a certain size and replaces them with an image of the same size. I have the replacement function working correctly using filter and replaceWith, however I noticed when testing the script I need to copy the style of the original element over to make sure it doesn't screw with the formatting of the page.
This is my current replacement script that works fine:
function findElements(Width,Height) {
$("*").filter(function () {
return $(this).width() == Width && $(this).height() == Height;
}).replaceWith("<img src='http://mydomain.com/image.jpg' />");
}
I found a script at jQuery CSS plugin that returns computed style of element to pseudo clone that element? to copy the styles over. I tried declaring the style variable but it is undefined. Not sure what to do:
(function($){
$.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;i<style.length;i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, 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;
}
return this.css();
}
})(jQuery);
function findElements(Width,Height) {
$("*").filter(function () {
return $(this).width() == Width && $(this).height() == Height;
var style = $(this).getStyleObject();
}).replaceWith("<img src='http://mydomain.com/image.jpg' style=style='"+ style +"' />");
}