Varin
Varin

Reputation: 2443

Get all CSS properties for a class or id with Javascript/JQuery

Is it possible to specify a class or an ID and get all the CSS rules for that particular class or ID. I don't mean an element, I want to specify a class and return all CSS for that class.

I know I can use .style to get inline styles but I don't need inline, it has to come from the stylesheet.

Is it even possible with JS? Can it access the .css file and return a list of properties for a certain class?

Apologies for no code, it's more of a theoretical question although if someone has a function at hand, I'd be happy to study it.

Upvotes: 2

Views: 3389

Answers (3)

M_Badrah
M_Badrah

Reputation: 485

using jquery :

$(your element Id or class ).attr('style') 

it will return all css Properties

left: 75px; top: -59px; transform: rotate(0deg) scaleX(2.32432) scaleY(3.83333); 

if you need just one or more (you know which prop you need)

$(your element Id or class).css([
      "width", "height", "fontSize", "fontFamily", 'textAlign', 'fontWeight', 
      'fontStyle','textDecoration','letterSpacing', 'lineHeight'])

I am using react and trying to avoid jquery but for style issues I did't find faster and easier

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

Use document#styleSheets and extract all rules from all stylesheets into array. Then filter the array by the selectorText.

Note: I've used a simple Array#includes to check if the requested selector appears in selectorText, but you might want to create a stricter check to prevent false positives. For example the selector text .demo can find rules for .demogorgon as well.

const findClassRules = (selector, stylesheet) => {
  // combine all rules from all stylesheets to a single array
  const allRules = stylesheet !== undefined ? 
    Array.from((document.styleSheets[stylesheet] || {}).cssRules || []) 
    :  
    [].concat(...Array.from(document.styleSheets).map(({ cssRules }) => Array.from(cssRules))); 
  
  // filter the rules by their selectorText
  return allRules.filter(({ selectorText }) => selectorText && selectorText.includes(selector)); 
};

console.log(findClassRules('.demo', 0));
.demo {
  color: red;
}

.demo::before {
  content: 'cats';
}

Upvotes: 3

Joe Lissner
Joe Lissner

Reputation: 2472

You can do:

window.getComputedStyle($('[your class name]')[0])

Check out https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle for more information.

Upvotes: 2

Related Questions