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

如何在JavaScript中获取li列表内指定span元素的文本内容

获取特定span标签内的文本内容

我有一个包含p标签的li标签,p标签内包含若干span标签。想要获取<span class="tag">{{role}}</span>中的"role"文本内容。当前尝试的代码如下:

Array.prototype.slice.call(document.querySelectorAll('ul[data-tag="userJoinedList"] li')).forEach(function(element) {
        console.log(element.innerHTML)
}

对应的HTML结构:

<ul data-tag="userJoinedList">
    {{#users}}
       <li class="users">
           <p>
              <span class="users">{{username}}</span> 
              <span class="tag">{{role}}</span>
           </p>
       </li>
    {{/users}}
</ul>

解决方案

你可以直接定位到目标.tag类的span元素,然后提取其文本内容,两种实现方式如下:

方式一:遍历li元素后查找内部span

Array.prototype.slice.call(document.querySelectorAll('ul[data-tag="userJoinedList"] li')).forEach(function(element) {
    const roleSpan = element.querySelector('.tag');
    if (roleSpan) {
        // 获取文本并去除首尾空格
        const roleText = roleSpan.textContent.trim();
        console.log(roleText);
    }
});

方式二:直接选中所有目标span(更高效)

document.querySelectorAll('ul[data-tag="userJoinedList"] li .tag').forEach(function(span) {
    console.log(span.textContent.trim());
});

说明

  • querySelector('.tag')会在当前li的后代元素中匹配第一个类名为tag的span
  • textContent用于获取元素的纯文本内容,trim()可以移除文本首尾的空白字符
  • 第二种写法直接定位到所有需要的span元素,减少了遍历层级,执行效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 05:27:32