given a class .test{color:red;....}, how do i get the style propertise by using javascript?
Asked
Active
Viewed 53 times
-2
-
Please explain better and provide some code of what you have tried so far – kapantzak Jan 08 '15 at 08:24
-
Add a little more information. What are you trying to achieve? Do you have some code for us to read? etc. – CunningFatalist Jan 08 '15 at 08:25
-
1Do you need css properties? If yes - var color = $( this ).css( "background-color" ); – fly_ua Jan 08 '15 at 08:25
-
I need the css properties even if the class is not currently used on the page. – Shai Jan 08 '15 at 08:30
-
Help u re-define questions: given a class .test{color:red;....}, how do i get the style propertise by using javascript? – Stupidfrog Jan 08 '15 at 08:42
-
Thanks @Stupidfrog Thats what I meant – Shai Jan 08 '15 at 08:48
-
possible duplicate of [Can jQuery get all CSS styles associated with an element?](http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element) – Divakar Gujjala Jan 08 '15 at 09:07
2 Answers
0
If you want to get the title of an element with class then it is some what similar to below code...
jQuery Code
$(selector).attr(attribute);
If you want to get the inline styles then use
$(".test").css('style');
After this you need to parse the string and base on the separator. Then you will get the key / value pairs of css properties.
In the same way if you want to get the css properties then
jQuery Code
$(selector).css(proprerty);
$(".test").css('width');

Divakar Gujjala
- 803
- 8
- 24
0
As I assume you need the properties even if the class is not present at the moment, consider the following:
- Create an element with that class on the fly
- Get its styles
- Remove it again
Example:
$('document').ready(function()
{
var $bar, styles,
markup = '<div class="foo" id="bar"></div>';
// add a temporary element
$('body').append( markup );
// get element
$bar = $('#bar');
// get style with jQuery.css
console.log( $bar.css('margin') );
// or: Get all computed styles
styles = getComputedStyle( $bar[0] );
// all computed styles
console.log( styles );
// read out the one you want
console.log( styles.margin );
// for more see
// https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle
// remove the element again
$bar.remove().detach();
});

CunningFatalist
- 453
- 1
- 9
- 21