JavaScript get Styles - javascript

Is it possible to get ALL of the styles for an object using JavaScript? Something like:
main.css
-------
#myLayer {
position: absolute;
width: 200px;
height: 100px;
color: #0000ff;
}
main.js
-------
var ob = document.getElementById("myLayer");
var pos = ob.(getPosition);
// Pos should equal "absolute" but
// ob.style.position would equal null
// any way to get absolute?

You are talking about what is known as Computed Style, check out these article on how to get it:
Get Styles on QuirksMode
Get Computed Style
Get the rendered style of an element
From the last article, here is a function:
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
How to use it:
CSS:
/* Element CSS*/
div#container{
font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
}
JS:
var elementFontSize = getStyle(document.getElementById("container"), "font-size");

You might use:
var ob = document.getElementById("myLayer");
var pos = ob.style.position;
Every CSS property has it's own object model. Usually those css properties that contain '-' are written using java model.
For example:
//getting background-color property
var ob = document.getElementById("myLayer");
var color = ob.style.backgroundColor;
If you want to get all the css properties that are defined for an object, you will have to list them one by one, because even if you did not set the property in your style sheet, an object will have it with the default value.

Polyfill to get the current CSS style of element using javascript ... Visit the link for more info
/**
* #desc : polyfill for getting the current CSS style of the element
* #param : elem - The Element for which to get the computed style.
* #param : prop - The Property for which to get the value
* #returns : The returned style value of the element
**/
var getCurrentStyle = function (ele, prop) {
var currStyle;
if (!window.getComputedStyle) {
currStyle = ele.currentStyle[prop];
} else {
currStyle = window.getComputedStyle(ele).getPropertyValue(prop);
}
return currStyle;
}
/** How to use **/
var element = document.getElementById("myElement");
getCurrentStyle(element, "width"); // returns the width value

Related

Modify previously defined style in JS

A function for creating style constructed as follows
function createStyle(css) {
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
style.type = "text/css";
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
var textNode = document.createTextNode(css);
style.append(textNode);
}
head.append(style);
}
inspired by Christoph and TomFuertes code. Then it is called to create a style with class name tab
createStyle(`
.tab button {
background: inherit;
float: left;
outline: none;
border: none;
padding: 8px 6px;
width: 60px;
cursor: pointer;
}
`);
and a HTML element using the style
var div = document.createElement("div");
div.className = "tab";
parent.append(div);
is also created. So it all works.
After that I need to modify the style with class name tab, where following code
var style = document.getElementsByTagName("style");
var css = style[0].innerHTML
var className = css.split(" ")[0].split(".")[1];
is used to get the style class name. I have managed to get the style class name tab and also the string containing the object in css.
The question is how I modify the style without I modify the string and recreate the style? Or if I have to do that, how I should delete the previous defined style if there are already some styles which I have not recorded the order for accessing them through array sytle[].
Proposed solution
Using How to change/remove CSS classes definitions at runtime? suggested by Achu I made this function
// Change style attribute with value
function changeStyleAttribute(style, attr, value) {
var N = document.styleSheets.length;
var styles = document.styleSheets;
for(var i = 0; i < N; i++)
{
if(styles[i].rules[0].selectorText == style)
styles[i].rules[0].style[attr] = value;
}
}
which is called
changeStyleAttribute(".tab", "width", "299px");
and works. I hope there is another better and simpler solution.
You'll want to use document.styleSheets[i].cssRules which is an array you need to parse through to find the one you want, and then rule.style.setProperty('font-size','10px',null);
Refer to this link: How to change/remove CSS classes definitions at runtime?.
Hope this helps.

Get a css parameter without creating an element [duplicate]

This question already has an answer here:
Query property value of a css class even if not in use
(1 answer)
Closed 7 years ago.
I dispose of the following class :
.specialCell {
padding-left: 10px;
}
I would like to use this value as a property in JS, eg
var specialCellLeftPadding = getCssValue('.specialCell', 'padding-left');
The only way I can think of would be to create an element with the wanted class and get the seeked attribute value :
var tmpElt = document.createElement('div');
tmpElt.className = 'specialCell';
document.body.appendChild(tmpElt);
var specialCellLeftPadding = getComputedProperties(tmpElt).getPropertyValue('padding-left');
document.body.removeChild(tmpElt);
Is it possible to achieve the same purpose without creating and adding an new element to the dom ? (assuming no element with this class exists).
You can query CSS information directly from stylesheets using the CSSOM. E.g.,
var stylesheet = document.styleSheets[0];
document.getElementById('output').innerHTML = stylesheet.cssRules[0].style.paddingLeft;
.test { padding-left: 12px; }
Padding left: <span id="output"></span>
Borrowing from the example of dystroy's answer, you can get a css value using the document.styleSheets property
Using the css
.specialCell {
padding-left: 10px;
}
and
function getCssProperty(cssclass, property) {
for (var i = 0; i < document.styleSheets.length; i++) {
var styleSheet = document.styleSheets[i];
var cssRules = styleSheet.rules || // chrome, IE
styleSheet.cssRules; // firefox
for (var ir = cssRules.length; ir-- > 0;) {
var rule = cssRules[ir];
if (rule.selectorText == "." + cssclass) {
return rule.style.getPropertyValue(property);
}
}
}
}
var prop = getCssProperty('specialCell', 'padding-left');
console.info(prop);
this example will print 10px in the console

how to check the value of display property of a header element?

I need to check the display property of a header element on the page. Based on it different operations are to be done. I tried using
document.getElementsByTagName('header')[0].style.display
and comparing it to various display attributes, but this is executing false part whatever property I check for.
Here is my html :
<body>
<header id="main">
<p>Test to find the display property of an element (header in this case).</p>
</header>
</body>
And here is my Javascript :
var test1 = document.createElement('div');
var test2 = document.createElement('div');
test1.innerText = 'Testing for block : ';
test2.innerText = 'Testing for none : ';
var body = document.getElementById('main');
if (document.getElementsByTagName('header')[0].style.display == 'block') {
test1.innerText = test1.innerText + 'true part is executed';
body.appendChild(test1);
} else {
test1.innerText = test1.innerText + 'false part is executed';
body.appendChild(test1);
}
if (document.getElementsByTagName('header')[0].style.display == 'none') {
test2.innerText = test2.innerText + 'true part is executed';
body.appendChild(test2);
} else {
test2.innerText = test2.innerText + 'false part is executed';
body.appendChild(test2);
}
I put this also on jsfiddle http://jsfiddle.net/n8zDc/1/
What am I doing wrong ?
You want to use window.getComputedStyle. You haven't defined a display property value anywhere in the DOM
var header = document.getElementById('main');
var style = window.getComputedStyle(header);
console.log(style.display);
The reason is that .style doesn't really compute which style is actually applied to the element, but simply the style attribute on the DOM (either the HTML, or applied through JavaScript). As an example, consider this CSS:
* {
float: right;
}
.foo {
float: left;
}
And HTML:
<div>Foo</div>
<div class='foo'>Bar</div>
Neither of these have any style values in them, yet their computed styles will have a bunch of values, browser defaults such as display: block, and the CSS rules applied to them.

How to get margin value of a div in plain JavaScript?

I can get height in jQuery with
$(item).outerHeight(true);
but how do I with JS?
I can get the height of the li with
document.getElementById(item).offsetHeight
but i will always get "" when I try margin-top:
document.getElementById(item).style.marginTop
The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).
To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).
Example:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".
Live Copy | Source
Also, you can create your own outerHeight for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
#yourElement {
margin-left: 10px;
}
<div id="yourElement"></div>
Here is my solution:
Step 1: Select the element
Step 2: Use getComputedStyle and provide the element to it
Step 3: Now access all the properties
const item = document.getElementbyId('your-element-id');
const style= getComputedStyle(item);
const itemTopmargin = style.marginTop;
console.log(itemTopmargin)
It will give you margin with px units like "16px" which you might not want.
You can extract the value using parseInt()
const marginTopNumber = parseInt(itemTopmargin)
console.log(marginTopNumber)
It will give you the numerical value only (without any units).

Incrementing the CSS padding-top property in Javascript

I have a CSS defined for a div
#myDiv
{
padding-top: 20px,
padding-bottom: 30px
}
In a JS function, I would like to increment the value of padding-top by 10px
function DoStuff()
{
var myDiv = document.getElementById('myDiv');
//Increment by 10px. Which property to use and how? something like..
//myDiv.style.paddingTop += 10px;
}
The .style property can only read inline styles defined on an element. It cannot read styles defined in stylesheets.
You need a library to get the value, or use something like (from this question):
function getStyle(elem, name) {
// J/S Pro Techniques p136
if (elem.style[name]) {
return elem.style[name];
} else if (elem.currentStyle) {
return elem.currentStyle[name];
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
} else {
return null;
}
}
Then your code becomes:
var element = document.getElementById('myDiv'),
padding = getStyle(element, 'paddingTop'); // eg "10px"
element.style.paddingTop = parseInt(padding, 10) + 10 + 'px';
References:
.style and inline vs stylesheet styles
getStyle function
radix (2nd) parameter to parseInt
You should be using jquery to do this sort of thing, as most other solutions won't be very cross browser compatible and you'll spend days pulling your hair out over it.
function Dostuff()
{
var currentPadding = $('#myDiv').css('padding-top');
$('#myDiv').css('padding-top', currentPadding + 1);
}
See jquery.com for more.

Categories