Reputation: 5570
Using Window.getComputedStyle()
one can get the computed propertyValue for any property using getPropertyValue(propertyKey)
.
Wondering if there is any method that can return a JavaScript object with all the computed propertyKey: propertyValue
{
...
propertyKey: propertyValue,
...
}
Something similar to Chrome Dev Tool
If not probably I need to write it myself.
Thanks!
Upvotes: 1
Views: 769
Reputation: 18734
The Window.getComputedStyle() method returns a CSSStyleDeclaration collection.
This is an object which includes declarations and indexed properties, if you want to create an object of declarations you just need to filter out the indexed properties,
try this:
var el = document.querySelector('#elem-container')
var o = window.getComputedStyle(el)
var res = Object.keys(o).reduce((ac,x) => {
if(isNaN(x))
ac[x] = o[x];
return ac;
},{})
console.log(res)
console.log(camelToHyphen(res)) // also prefix moz and webkit
function camelToHyphen(s){
return Object.keys(s).reduce((ac, x) => {
var k = x.replace(/[A-Z]|^webkit|^moz/g, (c => '-' + c.toLowerCase() )) // converts uppercase to - and lowercase
return Object.assign(ac, {[k] : s[x]})
},{})
}
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
<div id="elem-container">dummy</div>
Upvotes: 3
Reputation: 13089
While I'm not aware of a pre-rolled function which will do the work for us, it's fairly trivial to grab all of the properties as you've indicated you'd like to.
Here's some code that will achieve it. First, we define a function that will give us forEach functionality on non-array objects. Next, we get the computedStyle of the target element before finally iterating through the collection of returned CSSStyleDeclaration objects, adding the property name and value to an object we later return.
"use strict";
// useful for NodeList & HtmlCollection types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var computedStyle = getTheStyle( document.getElementById('elem-container') );
alert("Element has a height of: " + computedStyle.height + "\n" + "And a position of: " + computedStyle.position);
}
function getTheStyle(tgtElement)
{
var result = {}, properties = window.getComputedStyle(tgtElement, null);
forEach(
properties,
function(prop)
{
result[prop] = properties.getPropertyValue(prop);
}
);
console.log(result);
return result;
}
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
<div id="elem-container">dummy</div>
<div id="output"></div>
Upvotes: 3