如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
当前回答
您可以使用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')]";
其他回答
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
这就行了。 返回包含文本的节点数组。
function get_nodes_containing_text(selector, text) {
const elements = [...document.querySelectorAll(selector)];
return elements.filter(
(element) =>
element.childNodes[0]
&& element.childNodes[0].nodeValue
&& RegExp(text, "u").test(element.childNodes[0].nodeValue.trim())
);
}
在脚本中使用名为getElementInnerText的属性,它将获取该标记的内部内容。
document.getElementInnerText('a');
功能的方法。返回所有匹配元素的数组,并在检查时修整周围的空格。
function getElementsByText(str, tag = 'a') {
return Array.prototype.slice.call(document.getElementsByTagName(tag)).filter(el => el.textContent.trim() === str.trim());
}
使用
getElementsByText('Text here'); // second parameter is optional tag (default "a")
如果你在查看不同的标签,比如span或button
getElementsByText('Text here', 'span');
getElementsByText('Text here', 'button');
默认值标签= 'a'将需要Babel旧浏览器