【问题标题】:How to determine the number of elements in the same class with jquery? [duplicate]jquery如何判断同一个类的元素个数? [复制]
【发布时间】:2023-03-26 12:33:02
【问题描述】:

我的网站中有一些元素具有相同的类名 我想知道用 jquery 或 javascript 有多少这些元素?

【问题讨论】:

  • $('.className').length

标签: javascript jquery html


【解决方案1】:

使用 vanilla javascript,您可以运行:

document.getElementsByClassName('className').length;

document.querySelectorAll('.className').length;

使用 jQuery:

$('.className').size()

$('.className').length;

【讨论】:

    【解决方案2】:

    jQuery

    $('.className').length
    

    Javascript

    document.getElementsByClassName('className').length
    

    【讨论】:

      【解决方案3】:

      使用 jQuery 很容易:

      console.log($('.text').length);
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <span class="text">TEST</span><br/>
      <span class="text">TEST</span><br/>
      <span class="text">TEST</span><br/>
      <span class="text">TEST</span><br/>
      <span class="text">TEST</span><br/>
      <span class="text">TEST</span><br/>
      <span class="text">TEST</span><br/>
      <span class="text">TEST</span><br/>

      更新

      元素$('.text')实际上保存了所有类text的数组。

      【讨论】:

        【解决方案4】:

        jQuery 代码

        $('.class-name').length;
        

        【讨论】:

          猜你喜欢
          • 2011-08-06
          • 2020-02-14
          • 2013-06-04
          • 2018-02-07
          • 2014-07-18
          • 1970-01-01
          • 1970-01-01
          • 2017-03-05
          • 2016-12-07
          相关资源
          最近更新 更多