Get the Computed Style and Omit Defaults

Get the computed style and omit defaults

there you go,
i did this by adding a new dummy DOM element, to know which styles are default for any element.

/**
* IE does not have `getComputedStyle`
*/

window.getComputedStyle = window.getComputedStyle || function( element ) {
return element.currentStyle;
}

/**
* get computed style for an element, excluding any default styles
*
* @param {DOM} element
* @return {object} difference
*/

function getStylesWithoutDefaults( element ) {

// creating an empty dummy object to compare with
var dummy = document.createElement( 'element-' + ( new Date().getTime() ) );
document.body.appendChild( dummy );

// getting computed styles for both elements
var defaultStyles = getComputedStyle( dummy );
var elementStyles = getComputedStyle( element );

// calculating the difference
var diff = {};
for( var key in elementStyles ) {
if(elementStyles.hasOwnProperty(key)
&& defaultStyles[ key ] !== elementStyles[ key ] )
{
diff[ key ] = elementStyles[ key ];
}
}

// clear dom
dummy.remove();

return diff;
}

/**
* usage
*/

console.log( getStylesWithoutDefaults( document.getElementById( 'bar' ) ) );

Notes:

  • the result will have some extra properties, not only those you've mentioned.

demo - console should be opened

window.getComputedStyle(): How to Discard properties with default values?

Looking through the chromium source led me to:
node.ownerDocument.defaultView.getMatchedCSSRules(node, '');

I used it to create this function that will return only the styles defined by the style property or a matched CSS rule. Anything that appears in getComputedStyle but not here would be default, but I'm guess that this returns what you are actually looking for: the styles without the defaults.

// WebKit only
function getStyle(node) {
var styles = {};
var rules = node.ownerDocument.defaultView.getMatchedCSSRules(node, '');

var i = rules.length;
while (i--) {
merge(styles, rules[i].style)
}
merge(styles, node.style);

return styles;

function merge(obj, style) {
var i = style.length;
while(i--) {
var name = style[i];
obj[name] = style.getPropertyCSSValue(name);
}
}
}

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>

How do I get a computed style?

See this answer.

It's not jQuery but, in Firefox, Opera
and Safari you can use
window.getComputedStyle(element) to
get the computed styles for an element
and in IE you can use
element.currentStyle. The returned
objects are different in each case,
and I'm not sure how well either work
with elements and styles created using
Javascript, but perhaps they'll be
useful.

The iframe looks about 150px high to me. If its contents are 1196px high (and indeed, you appear to be exploring the html node, according to the screenshot) and that's what you want to get, then you should navigate into the DOM of the iframe's document and apply the above technique to that.

Javascript - window.getComputedStyle returns auto as element top and left properties

The getComputedStyle method returns the resolved value of CSS properties.

If the style sheet author(you) did not specify values for certain CSS properties(ie: top, right, bottom, and left) then the resolved value returned will be the default value. These CSS properties all have a default value of "auto".

If you cannot or don't want to specify a value yourself in the stylesheet and you only need coordinates relative to the top-left of the viewport, consider using Element.getBoundingClientRect():

<html><head>    <title>Test</title>    <style>        /* Remove default styling to ensure a top and left value of 0 */        body {margin:0; padding:0}        button {display:block}    </style>    <script type="text/javascript">        function test() {            var button = document.getElementsByTagName("button")[0],                style = window.getComputedStyle(button),                coordinates = button.getBoundingClientRect();
alert ( "top = " + coordinates.top + "\nleft = " + coordinates.left + "\nwidth = " + style.width + //63px "\nheight = " + style.height //24px ); } </script></head><body> <button id="buttonTest" onClick="test()" >Test it!</button></body></html>


Related Topics



Leave a reply



Submit