开发者

Is it possible to get all global/inherit css classes applied to an element?

I need a javascript function that can get me all the CSS classes applied to an element.

We have function like getComputedStyle(element,"") and currentStyle(), FF and IE respectively. But, these function only give me the CSS properties applied to the element, not the classes.

To make things more clear please see the following DOM structure.

<html>
 <head>
 <style>
.dd{
    font-weight:bold;
}
.dd span{
    border:solid 1px #ABABAB;
}
</style>
 </head>
 <body>
  <div class='dd'>  
    <span id='span1'>Hi this is a example</span>
  </div>
 </body>
</html>

Now what the javascript should is if i get the element 'span1' it should give me all the classes that are applied to this el开发者_如何学Cement. Say the output should be giving me ".dd span and .dd"


document.getElementById('span1').className;

and you can use .parentNode to get various parent classes.

And, if you give the topmost parent a position style, you could use this:

var topmost = document.getElementById('span1').offsetParent;

for(var x = 0; x < topmost.childNodes.length;x++) {
  alert(topmost.childNodes[x].className);
}

// Edit

It looks like you're trying to do a Firebug type of thing. A lot of users here on SO have tried the same. A good search might lead you to things you never dreamed of...muhahahaha....


As a continuation from Steve's answer, you can just loop through the parent nodes and list the class names for each parent node.

var listClasses = function(element){ 
    while(element){
        console.log(element.className);
        element = element.parentNode;
    }
}

To Use:

listClasses(target);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜