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

<a ...>SearchingText</a>

当前回答

function findByTextContent(needle, haystack, precise) { // needle: String, the string to be found within the elements. // haystack: String, a selector to be passed to document.querySelectorAll(), // NodeList, Array - to be iterated over within the function: // precise: Boolean, true - searches for that precise string, surrounded by // word-breaks, // false - searches for the string occurring anywhere var elems; // no haystack we quit here, to avoid having to search // the entire document: if (!haystack) { return false; } // if haystack is a string, we pass it to document.querySelectorAll(), // and turn the results into an Array: else if ('string' == typeof haystack) { elems = [].slice.call(document.querySelectorAll(haystack), 0); } // if haystack has a length property, we convert it to an Array // (if it's already an array, this is pointless, but not harmful): else if (haystack.length) { elems = [].slice.call(haystack, 0); } // work out whether we're looking at innerText (IE), or textContent // (in most other browsers) var textProp = 'textContent' in document ? 'textContent' : 'innerText', // creating a regex depending on whether we want a precise match, or not: reg = precise === true ? new RegExp('\\b' + needle + '\\b') : new RegExp(needle), // iterating over the elems array: found = elems.filter(function(el) { // returning the elements in which the text is, or includes, // the needle to be found: return reg.test(el[textProp]); }); return found.length ? found : false;; } findByTextContent('link', document.querySelectorAll('li'), false).forEach(function(elem) { elem.style.fontSize = '2em'; }); findByTextContent('link3', 'a').forEach(function(elem) { elem.style.color = '#f90'; }); <ul> <li><a href="#">link1</a> </li> <li><a href="#">link2</a> </li> <li><a href="#">link3</a> </li> <li><a href="#">link4</a> </li> <li><a href="#">link5</a> </li> </ul>

当然,还有一种更简单的方法:

var textProp = 'textContent' in document ? 'textContent' : 'innerText'; // directly converting the found 'a' elements into an Array, // then iterating over that array with Array.prototype.forEach(): [].slice.call(document.querySelectorAll('a'), 0).forEach(function(aEl) { // if the text of the aEl Node contains the text 'link1': if (aEl[textProp].indexOf('link1') > -1) { // we update its style: aEl.style.fontSize = '2em'; aEl.style.color = '#f90'; } }); <ul> <li><a href="#">link1</a> </li> <li><a href="#">link2</a> </li> <li><a href="#">link3</a> </li> <li><a href="#">link4</a> </li> <li><a href="#">link5</a> </li> </ul>

引用:

Array.prototype.filter()。 Array.prototype.forEach()。 Array.prototype.slice()。 有条件的('三元',评估?ifTrue: ifFalse)操作符。 Function.prototype.call()。 typeof算子。

其他回答

功能的方法。返回所有匹配元素的数组,并在检查时修整周围的空格。

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.getElementsByInnerText()获取多个元素(多个元素可能具有完全相同的文本),并使用document.getElementByInnerText()获取一个元素(第一次匹配)。

此外,你可以通过使用元素(例如someElement.getElementByInnerText())而不是文档来本地化搜索。

您可能需要调整它以使其跨浏览器或满足您的需求。

我认为代码是不言自明的,所以我将保持原样。

HTMLElement.prototype.getElementsByInnerText = function (text, escape) { var nodes = this.querySelectorAll("*"); var matches = []; for (var i = 0; i < nodes.length; i++) { if (nodes[i].innerText == text) { matches.push(nodes[i]); } } if (escape) { return matches; } var result = []; for (var i = 0; i < matches.length; i++) { var filter = matches[i].getElementsByInnerText(text, true); if (filter.length == 0) { result.push(matches[i]); } } return result; }; document.getElementsByInnerText = HTMLElement.prototype.getElementsByInnerText; HTMLElement.prototype.getElementByInnerText = function (text) { var result = this.getElementsByInnerText(text); if (result.length == 0) return null; return result[0]; } document.getElementByInnerText = HTMLElement.prototype.getElementByInnerText; console.log(document.getElementsByInnerText("Text1")); console.log(document.getElementsByInnerText("Text2")); console.log(document.getElementsByInnerText("Text4")); console.log(document.getElementsByInnerText("Text6")); console.log(document.getElementByInnerText("Text1")); console.log(document.getElementByInnerText("Text2")); console.log(document.getElementByInnerText("Text4")); console.log(document.getElementByInnerText("Text6")); <table> <tr> <td>Text1</td> </tr> <tr> <td>Text2</td> </tr> <tr> <td> <a href="#">Text2</a> </td> </tr> <tr> <td> <a href="#"><span>Text3</span></a> </td> </tr> <tr> <td> <a href="#">Special <span>Text4</span></a> </td> </tr> <tr> <td> Text5 <a href="#">Text6</a> Text7 </td> </tr> </table>

我发现,与其他答案相比,新语法的使用略短。所以我的建议是:

const callback = element => element.innerHTML == 'My research'

const elements = Array.from(document.getElementsByTagName('a'))
// [a, a, a, ...]

const result = elements.filter(callback)

console.log(result)
// [a]

JSfiddle.net

你可以使用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>