【问题标题】:How to get id from class [duplicate]如何从类中获取 id [重复]
【发布时间】:2016-10-25 14:27:56
【问题描述】:

我想从类选择器中获取 id 名称。我该怎么做?

<div class="tab-pane active popup_RC" id="Basic">

$(.tab-pane active) 我需要它的 ID Basic

【问题讨论】:

  • 应该是.tab-pane.active

标签: jquery jquery-selectors


【解决方案1】:

使用attr()方法获取属性

$('.tab-pane.active').attr('id')

console.log(
  $('.tab-pane.active').attr('id')
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab-pane active popup_RC" id="Basic">

或使用 prop() 获取 id 属性或从 dom 对象获取。

$('.tab-pane.active')[0].id
// or
$('.tab-pane.active').prop('id')

console.log(
  $('.tab-pane.active')[0].id
);

console.log(
  $('.tab-pane.active').prop('id')
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab-pane active popup_RC" id="Basic">

【讨论】:

    【解决方案2】:

    你可以使用属性选择器attr("id")

    $('.tab-pane.active').attr("id")
    

    【讨论】:

      【解决方案3】:

      可以使用.attr()获取元素的任意属性

      $('.tab-pane active').attr('id');
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-03
        • 2023-03-15
        • 2014-06-02
        • 1970-01-01
        相关资源
        最近更新 更多