carefulnow1
carefulnow1

Reputation: 841

How to read a CSS value from JavaScript?

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

Answers (7)

Paul Rad
Paul Rad

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

Vedant Terkar
Vedant Terkar

Reputation: 4682

Try This for getting all properties:

var css = document.getElementById('presentationProperty').style.cssText;
alert(css);

Upvotes: -1

Suman Bogati
Suman Bogati

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

shikhar.ja
shikhar.ja

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

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

Try this:

var x = document.getElementById('presentationProperty').style.display;

Upvotes: 1

Sirko
Sirko

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

musefan
musefan

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

Related Questions