如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
当前回答
我想你需要说得更具体一点,我们才能帮到你。
你是怎么发现的?Javascript ?PHP吗?Perl吗? 您可以将ID属性应用于标记吗?
如果文本是唯一的(或者实际上不是唯一的,但必须通过数组运行),则可以运行正则表达式来找到它。使用PHP的preg_match()可以解决这个问题。
如果你正在使用Javascript并且可以插入ID属性,那么你可以使用getElementById(' ID ')。然后可以通过DOM: https://developer.mozilla.org/en/DOM/element.1访问返回元素的属性。
其他回答
document.querySelectorAll('a').forEach(function (item) {
if (item.innerText == 'SearchingText') {
console.dir(item);
}
});
你可以这样做,不确定这是否被推荐,但对我来说很有效。
[... document.querySelectorAll('a')].filter(el => el.textContent.includes('sometext'));
我发现,与其他答案相比,新语法的使用略短。所以我的建议是:
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())
);
}
从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))