Phil
Phil

Reputation: 50426

Using Javascript how to get the pseudo CSS style of a dom node?

Hi I have an element (dom node) and it has a pseudo CSS hover CSS style. I want to use Javascript to get this CSS style, am in the Chrome web browser.

Upvotes: 1

Views: 714

Answers (2)

techfoobar
techfoobar

Reputation: 66693

You can get the computed styles (currently applied styles) of an element using window.getComputedStyle(element)

For your case, you can call the above when the element is hovered and use the saved style object later on for your purpose.

Ref: https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle

Demo: http://jsfiddle.net/ur297/

Code:

var hoverStyles = false;
$('.foo').hover(function() {
    hoverStyles = window.getComputedStyle(this);
    printStyles(hoverStyles );
}, function() {});

function printStyles(_styles) {
    console.log('Color: ' + _styles.color);
    console.log('Background Color: ' + _styles.backgroundColor);
}

Upvotes: 3

StaticVariable
StaticVariable

Reputation: 5283

  function getStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

and to get css like font-size

getStyle(document.getElementById("container"), "font-size");

Upvotes: 2

Related Questions