Get Element Stylesheet Style in JavaScript

Get Element StyleSheet Style in JavaScript

Is it possible to get only the
stylesheet specified styles of an
element (and return null if the style
is undefined)?

That's effectively what is done by the routine you present. The problem is, in most scenarios, most styles are not undefined - they're inherited and/or defined by the individual browser's internal stylesheet.

You could, with a whole lot of effort, iterate through all of the rules defining the style in question, in all of the stylesheets in the current view of the document, evaluate them for the element in question, and if none applied... and if none applied to a parent (or this particular style is not inherited)... then consider it undefined. This would be slow, and incredibly error-prone. I would not recommend trying it.

Perhaps you would do better to step back and ask why you would ever need such a thing?

how to get style values with js

i have no idea why it says style is null.do you?

It doesnt.
It says document.getElementById('square') returns null so youre reading the property style on null which results in the error.

That happens because your script is loaded (and executed) in the head. At this point the element with the ID "square" isnt existent in the DOM yet.

Move your script to below your element (see snippet) or mark it with async defer like this: <script src="index.js" async defer></script> to make it load and execute after DOM parsing is done.

Also accessing style will only show inline styles from the style attribute so that wont get you values from your stylesheet file (or inline stylesheets).

Use computedStyleMap() (see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap) to get the actual computed styles including all stylesheets.

body {
margin: 0;
}

#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
<html>

<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
</head>

<body>
<div id="square"></div>

<script>
console.log(document.getElementById('square').computedStyleMap().get('top').value);
</script>
</body>

</html>

Getting style of an element from css file with javascript

This isn't an Angular issue, it's just how CSS and Javascript interact. You need to use getComputedStyle to read style properties that were defined in a CSS file.

// This will work (because it's an inline style)console.log(document.getElementById('a').style.width)
// This won't work (because the style was defined in css):console.log(document.getElementById('b').style.width)
// getComputedStyle will work regardless of the source:console.log(window.getComputedStyle(document.getElementById('b')).width)
#b {width: 100px}
<div id="a" style="width: 100px">A</div><div id="b">B</div>

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 get the applied style from an element, excluding the default user agent styles

There is a read only property of document called 'styleSheets'.

var styleSheetList = document.styleSheets;

https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets

By using this, you can reach all the styles which are applied by the author.

There is a similar question about this but not a duplicate, in here:

Is it possible to check if certain CSS properties are defined inside the style tag with Javascript?

You can get the applied style from an element, excluding the default user agent styles using the accepted answer of that question i just mentioned.

That answer didn't supply the element's own style attribute content, so i have improved the code a bit:

var proto = Element.prototype;var slice = Function.call.bind(Array.prototype.slice);var matches = Function.call.bind(proto.matchesSelector ||                 proto.mozMatchesSelector || proto.webkitMatchesSelector ||                proto.msMatchesSelector || proto.oMatchesSelector);
// Returns true if a DOM Element matches a cssRulevar elementMatchCSSRule = function(element, cssRule) { return matches(element, cssRule.selectorText);};
// Returns true if a property is defined in a cssRulevar propertyInCSSRule = function(prop, cssRule) { return prop in cssRule.style && cssRule.style[prop] !== "";};
// Here we get the cssRules across all the stylesheets in one arrayvar cssRules = slice(document.styleSheets).reduce(function(rules, styleSheet) { return rules.concat(slice(styleSheet.cssRules));}, []);

var getAppliedCss = function(elm) { // get only the css rules that matches that element var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, elm)); var rules =[]; if(elementRules.length) { for(i = 0; i < elementRules.length; i++) { var e = elementRules[i]; rules.push({ order:i, text:e.cssText }) } } if(elm.getAttribute('style')) { rules.push({ order:elementRules.length, text:elm.getAttribute('style') }) } return rules;}

function showStyle(){var styleSheetList = document.styleSheets;// get a reference to an element, then...var div1 = document.getElementById("div1");
var rules = getAppliedCss(div1);
var str = '';for(i = 0; i < rules.length; i++) { var r = rules[i]; str += '<br/>Style Order: ' + r.order + ' | Style Text: ' + r.text; } document.getElementById("p1").innerHTML = str;
}
#div1 {float:left;width:100px;}
div {text-align:center;}
<div id="div1" style="font-size:14px;"> Lorem ipsum  </div><br/><br/><a href="javascript:;" onclick="showStyle()"> Show me the style. </a> <p id="p1"><p>

Get an elements style inherited from classes *not* style attribute

Well, I don't think you can get the style directly from the stylesheets. But I think you can use below code for a workaround:

if( typeof( $('#alice').attr('style') ) != 'undefined' ) { 
$('#alice').removeAttr('style');
var aliceSheets = $('.alice').css('color');
console.log(aliceSheets);
}

If you want to get the style only without changing the style of the element then you can add the style attribute back after reading the color.

How to programmatically check CSS styles for particular elements?

You can use window.getComputedStyle(). The returned value is a CSSStyleDeclaration, and you can access the properties directly using the dot notation or use .getPropertyValue('property name').

var p = document.querySelector('.demo');var style = window.getComputedStyle(p);
console.log(style);
console.log('style.color ', style.color);
// or
console.log('getPropertyValue(\'color\')', style.getPropertyValue('color'));
.demo {  color: red; }
<p class="demo">This is red</p>


Related Topics



Leave a reply



Submit