0

Is it somehow possible to get all properties of a class through JavaScript? Lets say I have a class

.menu { color: black; width: 10px; }

How can I get "color: black; width: 10px;" as a string through JavaScript?

Thank you!

1
  • To me this sounds like an odd question. It sounds like you want to manually apply the styles to nodes, instead of using the class. A single rule in CSS has little meaning due to the cascade, the C in CSS. The resulting style will depend on the other rules in your CSS files, the specifity of their selectors, the order of the rules, and the context of the node that matches these particular selectors in the document. Commented Apr 22, 2017 at 22:54

1 Answer 1

3

You can use getComputedStyle(). This will find all inline-style or css styling done in a css file..This returns all properties computed of the element

See snippet below

var el=document.getElementsByClassName("menu")[0];
style=getComputedStyle(el);
console.log(style);
.menu{
color:green;
background:blue;
opacity:1
}
<div class="menu"></div>

You can also get a specific property from the class in the above snippet, example

style.width
Sign up to request clarification or add additional context in comments.

4 Comments

also note that colors returned won't be in words (like "black" in question) or even hex if that's how they are set in css ... will be rgb or rgba depending on browser. To get "black" would require lots more additional work by developer
similar issue with dimensions like %, em etc
Thank you for your answer. getComputedStyle is what I've been using so far. But this returns properties from other classes also. What I need is it to return all properties of a specific class. :(
In that case you will have to dig into the innerHTML of all style tags and use some form a parser or regex to find that class. Be warned too, if you do this, it does not mean the rules in the class are valid because there may be other rules in other stylesheets or inline style overriding those rules of the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.