Reputation: 841
I was wondering how you could read and save to a variable the CSS value of a HTML element. For example say you have this:
<tr id="presentationProperty" style="display: none;">
I would want to be able to read the display: none property and save it to a variable inside JavaScript. Is this possible and if so, how?
Upvotes: 2
Views: 152
Reputation: 4882
Easy:
var display = document.getElementById('presentationProperty').style.display;
Globally, you can access to styles properties of an element like this:
var getStyle = function(elementID, prop) {
return document.getElementById(''+elementID+'').style[prop];
};
alert (getStyle('presentationProperty', 'display')); // block
alert (getStyle('presentationProperty', 'position'));
alert (getStyle('presentationProperty', 'backgroundColor'));
// ...
Upvotes: 3
Reputation: 4682
Try This for getting all properties:
var css = document.getElementById('presentationProperty').style.cssText;
alert(css);
Upvotes: -1
Reputation: 6349
You can use getComputedStyle()
to get applied css value on particular element, something like this.
HTML
<tr id="presentationProperty" style="display: none;">
javaScript
var tr= document.getElementById('presentationProperty');
var computedStyle = document.defaultView.getComputedStyle(tr);
var dispVal = computedStyle['display']
This would more usefule when you appied the css(display
) as external or internal css.
Upvotes: 1
Reputation: 467
You can simply do this:
var el = document.getElementById('presentationProperty');
console.log(el.style.display);
It however will return empty string if the element has no display property defined inside css (i.e. it is inheriting default display property).
Upvotes: 0
Reputation: 172448
Try this:
var x = document.getElementById('presentationProperty').style.display;
Upvotes: 1
Reputation: 74046
If you want to read the final style applied to an element, use getComputedStyle()
. This includes any style applied to the element, whether it is an external stylesheets, styles defined within the same document, element styles or styles applied by JavaScript.
var elem = document.getElementById("presentationProperty");
var theCSSprop = window.getComputedStyle(elem).getPropertyValue("display");
Upvotes: 1
Reputation: 48415
First you need to get the element, and then you can use the style
property:
var element = document.getElementById("presentationProperty");
var display = element.style.display;
See here for a full list of available style properties
Upvotes: 2