【问题标题】:How to get class-name of element with multiple classes but only knowing 1 of them如何获取具有多个类但只知道其中一个的元素的类名
【发布时间】:2017-08-20 10:12:17
【问题描述】:

如果元素有多个类(在 Javascript 中),我也会尝试获取所有包含类名的元素。例如:

<div class="one two three four">
<div class="one two three">
<div class="one two">
<div class="one">

所以我现在想要所有包含类“one”的类。所以在这种情况下,所有这些。如果我使用 getElementsByClassName 我只能指定 1 个类,或者我需要在那里编写确切的多个类。

任何建议都非常感谢!

【问题讨论】:

标签: javascript html


【解决方案1】:

您要查找的属性是 className。

HTML

<div id="myId" class="one">
    stuff 
</div>
<div id="myId" class="one two">
    stuff 
</div>

JS

var d= document.getElementById('myId');
alert(d.className);

【讨论】:

    【解决方案2】:

    你想要的应该是 'one' ,它将返回所有具有 'one' 作为类的元素,而不管该元素所属的其他类。

    document.getElementsByClassName('one')
    

    多个课程仅供参考

    document.getElementsByClassName('one two three')
    

    【讨论】:

      【解决方案3】:

      尝试编写一些代码并直接测试您的问题而不是在 SO 中提问会更容易(更快)。

      或者阅读getElementsByClassName的文档

      [叹气] 你不必指定确切的多个类。运行:

      document.getElementsByClassName("one")
      

      会给你一个包含四个 div 的数组。

      【讨论】:

        【解决方案4】:

        如果您想获取每个具有类的元素的完整类名,您可以这样做

        // list className of all elements containing the class 'two'
        Array.from(document.querySelectorAll('.two')).forEach(function(element) {
          console.log(element.className);
        });
        <div class="one two three four">
        <div class="one two three">
        <div class="one two">
        <div class="one">

        【讨论】:

          猜你喜欢
          • 2015-07-04
          • 1970-01-01
          • 1970-01-01
          • 2023-03-27
          • 2019-07-01
          • 2021-12-20
          • 1970-01-01
          相关资源
          最近更新 更多