如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
当前回答
在脚本中使用名为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旧浏览器
你可以使用jQuery:contains()选择器
var element = $( "a:contains('SearchingText')" );
document.querySelectorAll('a').forEach(function (item) {
if (item.innerText == 'SearchingText') {
console.dir(item);
}
});
你必须徒手穿越。
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`.
虽然有可能读懂里面的文字,但我认为你走错了方向。内部字符串是动态生成的吗?如果是这样,您可以在文本进入时为标记提供一个类或更好的ID。如果它是静态的,那就更容易了。