如何获得标签在html页面,如果我知道什么文本标签包含。 例如:

<a ...>SearchingText</a>

当前回答

document.querySelectorAll('a').forEach(function (item) {
    if (item.innerText == 'SearchingText') {
        console.dir(item);
    }
});

其他回答

虽然有可能读懂里面的文字,但我认为你走错了方向。内部字符串是动态生成的吗?如果是这样,您可以在文本进入时为标记提供一个类或更好的ID。如果它是静态的,那就更容易了。

从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))
document.querySelectorAll('a').forEach(function (item) {
    if (item.innerText == 'SearchingText') {
        console.dir(item);
    }
});

简单地将你的子字符串传递到下面一行:

外的HTML

document.documentElement.outerHTML.includes('substring')

内心的HTML

document.documentElement.innerHTML.includes('substring')

你可以使用这些来搜索整个文档并检索包含搜索词的标签:

function get_elements_by_inner(word) {
    res = []
    elems = [...document.getElementsByTagName('a')];
    elems.forEach((elem) => { 
        if(elem.outerHTML.includes(word)) {
            res.push(elem)
        }
    })
    return(res)
}

用法:

用户“T3rm1”在本页上被提到了多少次?

get_elements_by_inner("T3rm1").length

1

jQuery被提到了多少次?

get_elements_by_inner("jQuery").length

3

获取所有包含“Cybernetic”的元素:

get_elements_by_inner("Cybernetic")

你必须徒手穿越。

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`.