3

I need a JavaScript/jQuery way of "hijacking" a CSS definition that is not based on a class or ID.

An example CSS:

input {
    border: 1px solid red;
}

If I then have a document with, say, a <span> element in it, I'd want to add this element to this definition.

So I'd do $(this).magicAwesome(); and the red border defined in the input CSS definition would also be applied to this non-input element.

Is there a way to achieve this effect? I don't care if it's hackish. :)

Thanks a bunch in advance!

Emphram Stavanger
  • 4,158
  • 9
  • 35
  • 63
  • 3
    Why can you not just amend your CSS selector? – Rory McCrossan Mar 16 '12 at 15:01
  • A solution to this would basically mean that you'd found a browser bug. – Pointy Mar 16 '12 at 15:02
  • 1
    Long story short, the CSS definition is a part of a third-party library which I'm extending with a plug-in. I don't want to mess with the library's original code for obvious forward-compatibility reasons, but I do need to have a non-matching element assuming the same style. – Emphram Stavanger Mar 16 '12 at 15:06

3 Answers3

4

You can either read the computed style for a selected element, then copy that, or read the CSS declaration from the stylesheet itself. Reading stylesheets is a bit of a pain because of IE vs. Standards.

See: Dynamically add referenced stylesheet to inline styles

http://www.javascriptkit.com/domref/stylesheet.shtml

https://developer.mozilla.org/en/DOM/document.styleSheets

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
1

You can copy all styles from a temporary 'donor' element and set them to your span: http://jsfiddle.net/UxFUr/

It does everything you wanted:

  • it changes the styles of the span to the css styles of "input"
  • it's named magicAwesome!
  • bonus: it's hackish...

the code:

$.fn.magicAwesome=function(){
    var donor=$('<input />').appendTo('body');
    $(this).css(donor.getStyleObject());
    donor.remove();
}

And then set a click event or something to trigger the function $(this).magicAwesome();

I used the getStyleObject function from CopyCss

Willem
  • 5,364
  • 2
  • 23
  • 44
  • Not the same, as it would set all computed styles with their computed values at the time, you will lose all percentage values and other units except px. And since all rules are set, it will override any (and all) other styles set on the target element. – Qtax Mar 16 '12 at 15:31
  • True, but as far as I know this is the closest to what he wants, or he would have to change the span to an input... (and like I said: it's hackish). – Willem Mar 16 '12 at 15:47
0

If you know what you want duplicate from stylesheet, you can try this: http://jsfiddle.net/YHYQe/

giker
  • 4,165
  • 1
  • 18
  • 10