如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
当前回答
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>
其他回答
document.querySelectorAll('a').forEach(function (item) {
if (item.innerText == 'SearchingText') {
console.dir(item);
}
});
我发现,与其他答案相比,新语法的使用略短。所以我的建议是:
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
你必须徒手穿越。
var aTags = document.getElementsByTagName("a");
var searchText = "SearchingText";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].textContent == searchText) {
found = aTags[i];
break;
}
}
// Use `found`.
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>
在脚本中使用名为getElementInnerText的属性,它将获取该标记的内部内容。
document.getElementInnerText('a');