JavaScript Get Styles

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 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>

get HTML element style with Javascript

use window.getComputedStyle

read more https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

basically style property only read the inline style on the element

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 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 cssRule

var elementMatchCSSRule = function(element, cssRule) {

return matches(element, cssRule.selectorText);

};

// Returns true if a property is defined in a cssRule

var propertyInCSSRule = function(prop, cssRule) {

return prop in cssRule.style && cssRule.style[prop] !== "";

};

// Here we get the cssRules across all the stylesheets in one array

var 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>

JS - how to get content of internal style element ( style ... /style)

document.getElementsByTagName returns Array of Elements

so you need to access it with index

document.getElementsByTagName('style')[0].innerHTML

document.styleSheets is much useful if you want to get specific selector or modify something from style sheet

Example

var styleSheet = document.styleSheets[1]; 
// assuming second one is embedded style,
// since document.styleSheets also shows linked style sheets (like <link heref=".. >)

for (var i = 0; i < styleSheet.rules.length; i++) {
// if you are looking for selector '.main'
if (styleSheet.rules[i].selectorText === '.main') {
// get background color
var oldBg = styleSheet.rules[i].style.backgroundColor;

// set background color
styleSheet.rules[i].style.backgroundColor = '#ddd';
}
}

How to get Element's Style value assigned from a Class

You can use getComputedStyle to get the styles used on an element and not just on the style property.

var styles = getComputedStyle(document.getElementById('myDiv'));
var display = styles.getPropertyValue('display')
console.log(display);
.myDivStyle {display:none;}
<div id='myDiv' class='myDivStyle'>inner stuff</div>


Related Topics



Leave a reply



Submit