How to Find CSS Rules from an HTML Node via JavaScript

Is it possible to find CSS rules from an HTML node via JavaScript?

This is what you want. WebKit only. I found out about getMatchedCSSRules by looking at the chromium web inspector source.

  function getAppliedSelectors(node) {
var selectors = [];
var rules = node.ownerDocument.defaultView.getMatchedCSSRules(node, '');

var i = rules.length;
while (i--) {
selectors.push(rules[i].selectorText);
}
return selectors;
}

Find all CSS rules that apply to an element

EDIT: This answer is now deprecated and no longer works in Chrome 64+. Leaving for historical context. In fact that bug report links back to this question for alternative solutions to using this.


Seems I managed to answer my own question after another hour of research.

It's as simple as this:

window.getMatchedCSSRules(document.getElementById("description"))

(Works in WebKit/Chrome, possibly others too)

How do you read CSS rule values with JavaScript?

Adapted from here, building on scunliffe's answer:

function getStyle(className) {
var cssText = "";
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
cssText += classes[x].cssText || classes[x].style.cssText;
}
}
return cssText;
}

alert(getStyle('.test'));

How to get and extract matched css rules on dom-node?

What prevents you from mouse-selecting and copying (Ctrl-C, whatever) the contents of the "Matched CSS Rules" or "Computed Styles" section in the sidebar (am I missing the task you are trying to solve?)

There's a known issue with pasting the copied contents into well-known HTML-aware text editors (the CSS properties inside rules are rendered as a numbered list, which is actually a bug in the respective editors) but otherwise, if you want to manually grab a copy of all your matched CSS rules/computed style for a DOM element, this workflow should work for you.

3rd party edit

In the comment below it is recommended to use window.getMatchedCSSRules(). Using it in Chrome 62 returns this

VM1395:1 [Deprecation] 'getMatchedCSSRules()' is deprecated. For more
help, check
https://code.google.com/p/chromium/issues/detail?id=437569#c2

The discussion getMatchedCSSRules was started in november 2014 and contains this bit getMatchedCSSRules is non-standard and likely to be removed in the coming months. Relying on it is bad for cross-browser interop since major browsers like Firefox and IE won't be supported. It seems that M63 will start to remove it.

An alternative might be to use CSS Object Model (CSSOM)

Select all node that has certain css-rule without jQuery

You could read the loaded css rules using document.styleSheets. Then, find the rules that are setting the specific property, in your case style.color == "blue".

Then, get the selectorText from the rule, it will give you the selectors. It will be easy then to select the elements using document.querySelector() passing the obtained selectors as the parameter.

var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;for (var x = 0; x < classes.length; x++) {  var cls = classes[x];  if(cls.style.color == "blue") {    alert(cls.selectorText);        //Gets a node list of the elements matching the selector    var elements = document.querySelectorAll(cls.selectorText);  }}
html {  color: blue;}div.x {  color: blue;}

Is there a way to find out where a css rule is coming from?

You may use web inspector in Chrome.

Right click on failing element and select inspect element.

You should end up with web inspector window with two sections: left is html nodes tree and right is styles and properties of selected node. Failing element should be selected already.

Next you need to expand "Computed Style" tab and look for offending style.

When found, you'll see small triangle to the left of style definition - it is clickable. On click it should expand list of selectors that affects this style for this element. You'll see url to css for each of this. Bingo.

How to get an HTML element's style values in JavaScript?

The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.

Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.

The two ways have differences, for example, the IE element.currentStyle property expect that you access the CCS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc).

Also, the IE element.currentStyle will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.

I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:

function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}

The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.

I'm currently working on an article in the subject, you can follow the changes I make to this function here.

How to find all possible CSS Styles and Attributes of an Element?

You can check if the found elements are inside of other elements using jQuery $.contains()

More info here how to do this here: http://api.jquery.com/jQuery.contains/

So for your example to find if some found classes are inside set you can do:

$.each(foundElement, function(index, domElement){
if($.contains(domElement, $('.set'))) {
// domElement is inside the container with 'set' class
} else {
// domElement is not inside the container with 'set' class
}
});

How to get the inherited values of element from JavaScript

You can simply implement a pixel-to-rem converter and use that:

function convertPixelsToRem(pixels) {
return ((pixels.replace("px", "") / getComputedStyle(document.documentElement).fontSize.replace("px", "")) + "rem");
}

console.log(convertPixelsToRem(window.getDefaultComputedStyle(document.getElementById("new").querySelector(".h1"))["font-size"]));
<style>
#new {
font-size: 2rem;
}
</style>
<div id="new">
<h1 class="h1">This is a heading</h1>
<!–– Here h1 is inheriting font-size from div ––>
</div>


Related Topics



Leave a reply



Submit