如何获得标签在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>
其他回答
使用目前最现代的语法,它可以像这样非常干净地完成:
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))
当然,遗留浏览器不能处理这个,但是如果需要遗留支持,可以使用转译器。
你可以使用TreeWalker遍历DOM节点,并找到所有包含文本的文本节点,并返回它们的父节点:
const findNodeByContent = (text, root = document.body) => { const treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const nodeList = []; while (treeWalker.nextNode()) { const node = treeWalker.currentNode; if (node.nodeType === Node.TEXT_NODE && node.textContent.includes(text)) { nodeList.push(node.parentNode); } }; return nodeList; } const result = findNodeByContent('SearchingText'); console.log(result); <a ...>SearchingText</a>
你可以使用jQuery:contains()选择器
var element = $( "a:contains('SearchingText')" );
我想你需要说得更具体一点,我们才能帮到你。
你是怎么发现的?Javascript ?PHP吗?Perl吗? 您可以将ID属性应用于标记吗?
如果文本是唯一的(或者实际上不是唯一的,但必须通过数组运行),则可以运行正则表达式来找到它。使用PHP的preg_match()可以解决这个问题。
如果你正在使用Javascript并且可以插入ID属性,那么你可以使用getElementById(' ID ')。然后可以通过DOM: https://developer.mozilla.org/en/DOM/element.1访问返回元素的属性。
您可以使用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')]";