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

如何根据href前缀条件获取a元素的innertext?

获取href以指定文本开头的a元素的innerText

原生JavaScript实现

方法1:用CSS属性选择器直接筛选

借助document.querySelectorAll结合[href^="指定前缀"]选择器,可直接匹配href属性值以目标文本开头的a标签,再遍历提取innerText:

// 把"www"替换成你需要的前缀
const targetLinks = document.querySelectorAll('a[href^="www"]');

// 遍历输出每个符合条件的a元素文本
targetLinks.forEach(link => {
  console.log(link.innerText);
});

说明:[href^="xxx"]是CSS属性前缀匹配选择器,精准匹配标签上href属性的原始值开头。

方法2:手动遍历判断(更灵活)

如果需要更复杂的判断逻辑(比如不区分大小写、处理绝对URL等),可以遍历所有a标签后用startsWith方法判断:

const allLinks = document.getElementsByTagName('a');

for (const link of allLinks) {
  // 要匹配标签上的原始href值就用link.getAttribute('href')
  // 要匹配完整的绝对URL就直接用link.href
  if (link.getAttribute('href').startsWith('www')) {
    console.log(link.innerText);
  }
}

jQuery实现

如果项目使用jQuery,可以用同样的属性选择器快速筛选:

// 把"www"替换成目标前缀
$('a[href^="www"]').each(function() {
  // 提取文本并输出
  console.log($(this).text());
});

示例验证

针对这段代码:

<a href="www.url.com">text</a>
<a href="other.url.com">ignore</a>

用上述方法筛选前缀为"www"的a标签,会得到输出:text

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:48:27