如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
当前回答
从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))
其他回答
使用目前最现代的语法,它可以像这样非常干净地完成:
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))
当然,遗留浏览器不能处理这个,但是如果需要遗留支持,可以使用转译器。
从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))
您可以使用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')]";
简单地将你的子字符串传递到下面一行:
外的HTML
document.documentElement.outerHTML.includes('substring')
内心的HTML
document.documentElement.innerHTML.includes('substring')
你可以使用这些来搜索整个文档并检索包含搜索词的标签:
function get_elements_by_inner(word) {
res = []
elems = [...document.getElementsByTagName('a')];
elems.forEach((elem) => {
if(elem.outerHTML.includes(word)) {
res.push(elem)
}
})
return(res)
}
用法:
用户“T3rm1”在本页上被提到了多少次?
get_elements_by_inner("T3rm1").length
1
jQuery被提到了多少次?
get_elements_by_inner("jQuery").length
3
获取所有包含“Cybernetic”的元素:
get_elements_by_inner("Cybernetic")
我发现,与其他答案相比,新语法的使用略短。所以我的建议是:
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