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

<a ...>SearchingText</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旧浏览器

其他回答

const el = Array.from(document.body.querySelectorAll('a')).find(elm => elm.textContent.toLowerCase().include('search text')); const el2 = document.evaluate('//a[contains(text(text)]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; console.log(EL, EL2); <a href=“#”>text1</a> <a href=“#”>text2</a> <a href=“#”>搜索文本</a> <a href=“#”>text3</a> <a href=“#”>text4</a> <a href=“#”>text5</a>

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

你可以使用TreeWalker遍历DOM节点,并找到所有包含文本的文本节点,并返回它们的父节点:

const findNodeByContent = (text, root = document.body) => { const treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const nodeList = []; while (treeWalker.nextNode()) { const node = treeWalker.currentNode; if (node.nodeType === Node.TEXT_NODE && node.textContent.includes(text)) { nodeList.push(node.parentNode); } }; return nodeList; } const result = findNodeByContent('SearchingText'); console.log(result); <a ...>SearchingText</a>

在脚本中使用名为getElementInnerText的属性,它将获取该标记的内部内容。

document.getElementInnerText('a');