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

如何使用JavaScript选择文本为print的所有<a>标签?

纯JS实现选择所有文本为"print"的标签

嘿,这里有几种不用jQuery的纯JavaScript方案,帮你搞定需求:

方法1:querySelectorAll + 数组过滤

先获取所有<a>标签,再筛选出文本内容严格等于"print"的元素。如果担心文本前后有空格,可以加上trim()处理更严谨:

// 获取所有a标签并转换成数组
const allLinks = Array.from(document.querySelectorAll('a'));
// 筛选文本为"print"的链接
const printLinks = allLinks.filter(link => link.textContent.trim() === 'print');

// 遍历结果做后续操作
printLinks.forEach(link => {
  console.log(link.href);
});

方法2:getElementsByTagName + 循环遍历

这是更传统的DOM遍历方式,兼容性很好(甚至支持旧版浏览器):

const allLinks = document.getElementsByTagName('a');
const printLinks = [];

// 遍历所有a标签
for (let i = 0; i < allLinks.length; i++) {
  const link = allLinks[i];
  if (link.textContent.trim() === 'print') {
    printLinks.push(link);
  }
}

// 使用结果
printLinks.forEach(link => {
  // 比如给这些链接加个样式
  link.style.color = 'red';
});

方法3:XPath 直接匹配

利用XPath的文本匹配能力,可以一步定位到目标元素:

const xpathResult = document.evaluate(
  "//a[text()='print']", // XPath表达式,匹配文本为print的a标签
  document,
  null,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null
);

const printLinks = [];
// 提取结果
for (let i = 0; i < xpathResult.snapshotLength; i++) {
  printLinks.push(xpathResult.snapshotItem(i));
}

如果要兼容文本前后的空格,XPath表达式可以改成"//a[normalize-space(text())='print']",和trim()效果类似。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:17:46