Search code examples
jquerycssdompseudo-class

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.


Solution

  • 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);
    }