You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从带有active类的<li>标签中获取内部<a>标签的文本?

How to Extract the Text from the Tag Inside an Active
  • Element
  • First, let's look at your sample HTML to understand the structure:

    <li role="tab" class="ui-state-default ui-corner-top ui-tabs-active ui-state-active" aria-selected="true">
      <a href="#ContentPlaceHolder1_C1Tab1_tabIntake" tabindex="-1">Intake</a>
    </li>
    

    Here are a few straightforward ways to grab the "Intake" text when the <li> has an active class (in this case, ui-tabs-active or ui-state-active):

    Vanilla JavaScript (No Frameworks)

    Using querySelector

    This is my go-to for clean, modern JS. Target the active <li> and then its child <a>:

    // Grab the active li (adjust the class selector to match your actual active class)
    const activeTab = document.querySelector('li.ui-tabs-active');
    
    // Make sure we found an active element before proceeding
    if (activeTab) {
      const tabText = activeTab.querySelector('a').textContent;
      console.log(tabText); // Logs "Intake"
    }
    

    Pro tip: If you want to be extra specific, combine both active classes: li.ui-tabs-active.ui-state-active.

    Using getElementsByClassName

    If you prefer this method (though querySelector is more flexible):

    const activeTabs = document.getElementsByClassName('ui-tabs-active');
    
    // Check if there's at least one active tab
    if (activeTabs.length > 0) {
      const tabText = activeTabs[0].querySelector('a').textContent;
      console.log(tabText);
    }
    

    jQuery Solution (If You're Using jQuery)

    If your project uses jQuery, this is super concise:

    const tabText = $('li.ui-tabs-active a').text();
    console.log(tabText); // Outputs "Intake"
    

    Important Reminders

    • Double-check the active class name: In your example, it's ui-tabs-active, but other frameworks (like Bootstrap) use just active. Adjust the selector to match your actual code.
    • Always add checks (like the if statements) to avoid errors if there's no active <li> on the page.

    内容的提问来源于stack exchange,提问作者RackM

    相关产品推荐
    方舟 Agent Plan

    超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

    最近更新时间:2026.05.14 07:17:19