David
David

Reputation: 4873

Getting CSS styles that are set in a style sheet with native Javascript

I'm having a couple issues where I need to get the styles of an element with native JS (Not JQ). However, using something like elem.style.property returns "" because the actual HTML element doesn't have it set on it.

To make things more specific, one thing I need to get is the display value of an element, but elem.style.display gives "", but I need to know "block" or "none"

I understand WHY that's happening; I just need to know the proper way to get that value with native JS.

Thanks.

Upvotes: 1

Views: 92

Answers (1)

SW4
SW4

Reputation: 71150

Unless you have set the style directly on the element itself within your HTML you need to use either currentStyle or getComputedStyle e.g:

function getStyle(el,styleProp)
{
    if (el.currentStyle)
        return el.currentStyle[styleProp];

    return document.defaultView.getComputedStyle(el,null)[styleProp];
}

So for your purposes, you can call:

getStyle(element, 'visibility');

Upvotes: 1

Related Questions