2

I have the following CSS

.EggChart {
    width: 5000px;
    height: 400px;
}

and would like to read the value of height from the CSS class specification, either using raw JavaScript or in jQuery. If the class has been applied to an element of the DOM this seems straightforward: I'd select the elements of the DOM with this class and read their CSS attributes, but if the class has not been applied to any DOM element how would I do this?

dumbledad
  • 16,305
  • 23
  • 120
  • 273

1 Answers1

3

For simple CSS properties with fixed, constant values such as the ones given above, you can create a dummy element, then get the computed value for the property you're looking for.

Using vanilla JavaScript:

var el = document.createElement('div');
el.className = 'EggChart';
console.log(window.getComputedStyle(el).getPropertyValue('height'));

Using jQuery:

console.log($('<div class="EggChart"></div>').css('height'));
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • That certainly works (+1) but is it really the only way; are we unable to access the CSS specifications in a page through JavaScript directly? – dumbledad Apr 27 '14 at 10:36
  • 2
    @dumbledad: You'll have to parse the document stylesheet, which is an entirely different league in itself... – BoltClock Apr 27 '14 at 10:37
  • Eek - too right! That I do not want to embark on. – dumbledad Apr 27 '14 at 10:38
  • 1
    @dumbledad For direct manipulation of CSS stylesheet through JS, take a look here: http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript – caffeinated.tech Apr 27 '14 at 10:49