如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
如何获得标签在html页面,如果我知道什么文本标签包含。 例如:
<a ...>SearchingText</a>
当前回答
这就行了。 返回包含文本的节点数组。
function get_nodes_containing_text(selector, text) {
const elements = [...document.querySelectorAll(selector)];
return elements.filter(
(element) =>
element.childNodes[0]
&& element.childNodes[0].nodeValue
&& RegExp(text, "u").test(element.childNodes[0].nodeValue.trim())
);
}
其他回答
您可以使用xpath来实现这一点
var xpath = "//a[text()='SearchingText']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
你也可以使用xpath搜索包含文本的元素:
var xpath = "//a[contains(text(),'Searching')]";
你可以使用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>
使用目前最现代的语法,它可以像这样非常干净地完成:
for (const a of document.querySelectorAll("a")) {
if (a.textContent.includes("your search term")) {
console.log(a.textContent)
}
}
或者使用单独的过滤器:
[...document.querySelectorAll("a")]
.filter(a => a.textContent.includes("your search term"))
.forEach(a => console.log(a.textContent))
当然,遗留浏览器不能处理这个,但是如果需要遗留支持,可以使用转译器。
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旧浏览器