如何获得标签在html页面,如果我知道什么文本标签包含。 例如:

<a ...>SearchingText</a>

当前回答

我发现,与其他答案相比,新语法的使用略短。所以我的建议是:

const callback = element => element.innerHTML == 'My research'

const elements = Array.from(document.getElementsByTagName('a'))
// [a, a, a, ...]

const result = elements.filter(callback)

console.log(result)
// [a]

JSfiddle.net

其他回答

您可以使用xpath来实现这一点

var xpath = "//a[text()='SearchingText']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

你也可以使用xpath搜索包含文本的元素:

var xpath = "//a[contains(text(),'Searching')]";

从user1106925获取filter方法,如果需要,在<=IE11中工作

你可以将展开运算符替换为:

[] .slice.call (document.querySelectorAll(“a”))

和包含调用a.textContent。匹配(“你的搜索词”)

这很简单:

[].slice.call(document.querySelectorAll("a"))
   .filter(a => a.textContent.match("your search term"))
   .forEach(a => console.log(a.textContent))
document.querySelectorAll('a').forEach(function (item) {
    if (item.innerText == 'SearchingText') {
        console.dir(item);
    }
});

使用目前最现代的语法,它可以像这样非常干净地完成:

for (const a of document.querySelectorAll("a")) {
  if (a.textContent.includes("your search term")) {
    console.log(a.textContent)
  }
}

或者使用单独的过滤器:

[...document.querySelectorAll("a")]
   .filter(a => a.textContent.includes("your search term"))
   .forEach(a => console.log(a.textContent))

当然,遗留浏览器不能处理这个,但是如果需要遗留支持,可以使用转译器。

const el = Array.from(document.body.querySelectorAll('a')).find(elm => elm.textContent.toLowerCase().include('search text')); const el2 = document.evaluate('//a[contains(text(text)]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; console.log(EL, EL2); <a href=“#”>text1</a> <a href=“#”>text2</a> <a href=“#”>搜索文本</a> <a href=“#”>text3</a> <a href=“#”>text4</a> <a href=“#”>text5</a>