如何获得标签在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))
其他回答
你必须徒手穿越。
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`.
这就行了。 返回包含文本的节点数组。
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())
);
}
功能的方法。返回所有匹配元素的数组,并在检查时修整周围的空格。
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旧浏览器
你可以这样做,不确定这是否被推荐,但对我来说很有效。
[... document.querySelectorAll('a')].filter(el => el.textContent.includes('sometext'));
你可以使用jQuery:contains()选择器
var element = $( "a:contains('SearchingText')" );