0

I'm wondering whether there is a JQuery function that I can use to apply the CSS from a given element to another element. I'm talking about the exact CSS; nothing more applied due to inheritance.

To be more specific:

<div id="d1">
    <p id="p1">Here is some text.</p>
</div>

<div id="d2">
    <p id="p2">Here is some other text.</p>
    <!-- I want this text in p2 to have the same styling as the text in p1, even after the inheritances of the divs are factored. -->
</div>

<script type="text/javascript">
    $(...).(...); // ??????????????
</script>

If JQuery has such a function, it will save me an hour of trying to use my own stylesheet (I'm using a CMS that has a master style sheet that I can't change) to figuring out how to override/add a million properties.

Jonathan M
  • 17,145
  • 9
  • 58
  • 91
user4055428
  • 1,137
  • 2
  • 7
  • 5

1 Answers1

1

Though not compatible with Opera, this should accomplish your goal: http://jsfiddle.net/6o3f3em6/1/

  • Use getComputedStyle to get all CSS attributes of target element
  • Stringify the object into CSS
  • Apply the cssText to the receiving element

Here is the relevant code:

var target = document.querySelector('#p1');
var receiver = document.querySelector('#p2');
var styles   = getComputedStyle(target);

var cssText = '';
for(var style in styles){
    cssText += style+':'+styles[style];
}

receiver.style.cssText = cssText;
Rob M.
  • 35,491
  • 6
  • 51
  • 50