I am reading through an advance JavaScript book where they elaborated about the style object and its new properties added in DOM 2. To grasp the concept I made a small comparison program to see how the getPropertyValue
and ComputedStyles values behave. Here is the program below
<!DOCTYPE html>
<html>
<head>
<title>Style comparison</title>
<style type="text/css">
#myDiv2
{
background-color: brown;
height: 200px;
}
</style>
</head>
<body>
<h1>Comparison</h1>
<div>
<h2>Using getPropertyValue function - style object</h2>
<div id="myDiv" style="background-color: blue; width:100px; border: 1px solid black"></div>
<input type="button" value="Get property Value on inline style" onclick="getPropertyValue()">
</div>
<div>
<h2>Using documentView.getComputedStyles - DOM 2 methods</h2>
<div id="myDiv2"></div>
<input type="button" value="getComputedStyles" onclick="getComputedStyles()">
</div>
<script type="text/javascript">
function getPropertyValue() {
var div = document.getElementById("myDiv");
var properties = new Array();
for(var i = 0, len = div.style.length; i < len; i++) {
var propertyName = div.style[i];
var value = div.style.getPropertyValue(propertyName);
properties.push(propertyName + " " + value);
}
alert(properties.join("\n"));
}
function getComputedStyles() {
var div = document.getElementById("myDiv2");
var computedStyles = document.defaultView.getComputedStyle(div, null);
alert(computedStyles.backgroundColor);
alert(computedStyles.height);
/*for(var i=0, len=computedStyles.length; i<len; i++){
alert(computedStyles[i]);
}*/
}
</script>
</body>
</html>
So based on this, I do understand that we use getPropertyValue
on inline style css to access the attributes name and values. However, getComputedStyle
returns the attributes values that are inside a <style>
or external style sheet. My question now is how can I access attributes names and values using getComputedStyles like the ones I can access with getPropertyValue
?
Edit: To better rephrase my question. So using var computedStyles = document.defaultView.getComputedStyles("myDiv2", null) I can access the attributes value of background-color like this computedStyles.backgroundColor. However, how can I access the attribute name itself? Hope it makes it clear. Thanks
You were close to the answer...
window.getComputedStyle(div, null).getPropertyValue("background-color");
or
document.defaultView.getComputedStyle(div, null).getPropertyValue("background-color")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.