问题
I tried to print the list of attributes values in a specific CSS class with the getElementsByClassName method like below :
<html>
<head>
<style>
.toto {
width:200px;
height:50px;
background-color:red;
}
</style>
</head>
<body>
<div id="lol" class="toto"></div>
<script language="javascript" type="text/javascript">
var toto = document.getElementsByClassName('toto');
if (toto) {
for (int i; i < toto.length; i++)
document.write(toto[i]);
}
</script>
</body>
</html>
But toto.length = 1 in all cases. I would like to print the values '200px', '50px' et 'red'. Does anyone can help me ? Thanks a lot in advance for your help.
回答1:
If you get a reference to an element through JavaScript you can generally only get CSS properties that have been set through inline CSS using the style-attribute of the element. Properties applied through CSS can not be read through the element as properties of that element.
You can however use window.getComputedStyle() within your loop to get the final computed CSS that has been applied to the element.
In your case it would be something like:
var toto = document.getElementsByClassName('toto');
if (toto) {
for (int i; i < toto.length; i++)
// Log the height of each element
console.log(getComputedStyle(toto[i], null).getPropertyValue("height"));
}
}
Notice that the browser-support is somewhat limited (IE9+).
回答2:
I think you have misunderstood what getElementsByClassName
does.
getElementsByClassName
returns all HTML elements (tags) that have a class assigned - in your example this is one div
, which is why toto.length == 1
.
I'm not aware of any DOM methods for enumerating properties for a given CSS selector. However you can use tools like FireBug or Chrome's developer tools to inspect elements and see which CSS rules have been applied, and which properties have been modified.
回答3:
I won't repeat what others have yet pointed regarding getElementsByClassName
returning more than one elements, but I think your approach isn't the best one if you're interested in knowing what's in your style and not what's in a specific element (on which many styles are usually applied).
Here's a solution working even without element having the class toto
:
function findStyle(selector) {
for (var i=document.styleSheets.length; i-->0;) {
for (var j = document.styleSheets[i].cssRules.length; j-->0;) {
var r = document.styleSheets[i].cssRules[j];
if (r.selectorText==selector) return r;
}
}
}
var style = findStyle('.toto');
console.log(style.style.width, style.style.height, style.style['background-color']);
This logs on the console 200px 50px red
Demonstration
来源:https://stackoverflow.com/questions/14318209/print-list-of-attributes-from-a-css-class