如何获得标签在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))
其他回答
你可以使用jQuery:contains()选择器
var element = $( "a:contains('SearchingText')" );
功能的方法。返回所有匹配元素的数组,并在检查时修整周围的空格。
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').forEach(function (item) {
if (item.innerText == 'SearchingText') {
console.dir(item);
}
});
从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))
虽然有可能读懂里面的文字,但我认为你走错了方向。内部字符串是动态生成的吗?如果是这样,您可以在文本进入时为标记提供一个类或更好的ID。如果它是静态的,那就更容易了。