是否有可能将所有全局/继承CSS类应用于一个元素?

发布于 2024-09-30 09:09:12 字数 579 浏览 0 评论 0原文

我需要一个 javascript 函数来获取应用于元素的所有 CSS 类。

我们有像 getComputedStyle(element,"") 和 currentStyle() 这样的函数,分别是 FF 和 IE。 但是,这些函数只提供应用于元素的 CSS 属性,而不是类。

为了让事情更清楚,请查看以下 DOM 结构。

<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>

现在,如果我得到元素“span1”,javascript 应该为我提供应用于该元素的所有类。假设输出应该给我“.dd span and .dd”

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 element. Say the output should be giving me ".dd span and .dd"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

听闻余生 2024-10-07 09:09:13
document.getElementById('span1').className;

并且可以使用.parentNode来获取各种父类。

而且,如果你给最顶层的父级一个 position 样式,你可以使用这个:

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

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

// Edit

它看起来像你正在尝试做 Firebug 类型的事情。 SO 上的很多用户都尝试过同样的操作。一次好的搜索可能会带你找到你从未梦想过的东西......哈哈哈哈哈哈......

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....

一梦等七年七年为一梦 2024-10-07 09:09:13

作为史蒂夫回答的延续,您可以循环遍历父节点并列出每个父节点的类名称。

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

使用方法:

listClasses(target);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文