-2

given a class .test{color:red;....}, how do i get the style propertise by using javascript?

Shai
  • 355
  • 2
  • 5
  • 18

2 Answers2

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');

Demo: http://jsfiddle.net/s2xcmsvx/

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:

  1. Create an element with that class on the fly
  2. Get its styles
  3. 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();
});

Fiddle

CunningFatalist
  • 453
  • 1
  • 9
  • 21