dub*_*tor 114 javascript jquery innertext
如果我知道文本标签包含什么,如何在html页面中获取标签.例如:
<a ...>SearchingText</a>
Run Code Online (Sandbox Code Playgroud)
Aug*_*aas 116
你必须手工遍历.
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`.
Run Code Online (Sandbox Code Playgroud)
car*_*ott 113
您可以使用xpath来完成此任务
var xpath = "//a[text()='SearchingText']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Run Code Online (Sandbox Code Playgroud)
您还可以使用此xpath搜索包含某些文本的元素:
var xpath = "//a[contains(text(),'Searching')]";
Run Code Online (Sandbox Code Playgroud)
Mou*_*eer 30
你可以使用jQuery :contains()选择器
var element = $( "a:contains('SearchingText')" );
Run Code Online (Sandbox Code Playgroud)
小智 30
使用目前最现代的语法,它可以非常干净地完成,如下所示:
for (const a of document.querySelectorAll("a")) {
if (a.textContent.includes("your search term")) {
console.log(a.textContent)
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用单独的过滤器:
[...document.querySelectorAll("a")]
.filter(a => a.textContent.includes("your search term"))
.forEach(a => console.log(a.textContent))
Run Code Online (Sandbox Code Playgroud)
当然,传统浏览器不会处理此问题,但如果需要传统支持,您可以使用转换器.
Dav*_*mas 14
虽然已经有一段时间了,而且你已经(很久以来)接受了答案,但我认为我会提供更新的方法:
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';
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
当然,更简单的方法仍然是:
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';
}
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
参考文献:
Array.prototype.filter().Array.prototype.forEach().Array.prototype.slice().assessment ? ifTrue : ifFalse)运算符.Function.prototype.call().typeof运营商.Paw*_*wel 11
功能方法.返回所有匹配元素的数组,并在检查时修剪周围的空格.
function getElementsByText(str, tag = 'a') {
return Array.prototype.slice.call(document.getElementsByTagName(tag)).filter(el => el.textContent.trim() === str.trim());
}
Run Code Online (Sandbox Code Playgroud)
用法
getElementsByText('Text here'); // second parameter is optional tag (default "a")
Run Code Online (Sandbox Code Playgroud)
如果你正在查看不同的标签,例如跨度或按钮
getElementsByText('Text here', 'span');
getElementsByText('Text here', 'button');
Run Code Online (Sandbox Code Playgroud)
对于旧浏览器,默认值tag ='a'将需要Babel
只需将您的子字符串传递到以下行:
外部 HTML
document.documentElement.outerHTML.includes('substring')
Run Code Online (Sandbox Code Playgroud)
内部 HTML
document.documentElement.innerHTML.includes('substring')
Run Code Online (Sandbox Code Playgroud)
您可以使用这些来搜索整个文档并检索包含搜索词的标签:
function get_elements_by_inner(word) {
res = []
elems = [...document.getElementsByTagName('a')];
elems.forEach((elem) => {
if(elem.outerHTML.includes(word)) {
res.push(elem)
}
})
return(res)
}
Run Code Online (Sandbox Code Playgroud)
用法:
用户“T3rm1”在本页提及多少次?
get_elements_by_inner("T3rm1").length
Run Code Online (Sandbox Code Playgroud)
1
jQuery 被提及多少次?
get_elements_by_inner("jQuery").length
Run Code Online (Sandbox Code Playgroud)
3
获取所有包含“控制论”一词的元素:
get_elements_by_inner("Cybernetic")
Run Code Online (Sandbox Code Playgroud)
小智 9
你可以这样做,不确定是否推荐这样做,但它对我有用。
[... document.querySelectorAll('a')].filter(el => el.textContent.includes('sometext'));
Run Code Online (Sandbox Code Playgroud)
小智 6
document.querySelectorAll('a').forEach(function (item) {
if (item.innerText == 'SearchingText') {
console.dir(item);
}
});
Run Code Online (Sandbox Code Playgroud)
I found the use of the newer syntax a little bit shorter compared to the others answer. So here's my proposal:
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]
Run Code Online (Sandbox Code Playgroud)
您可以使用 aTreeWalker来遍历 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);Run Code Online (Sandbox Code Playgroud)
<a ...>SearchingText</a>Run Code Online (Sandbox Code Playgroud)
如果需要,从在 <=IE11 中工作的user1106925获取过滤器方法
您可以将扩展运算符替换为:
[].slice.call(document.querySelectorAll("a"))
和包括调用 a.textContent.match("your search term")
它工作得非常整洁:
[].slice.call(document.querySelectorAll("a"))
.filter(a => a.textContent.match("your search term"))
.forEach(a => console.log(a.textContent))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
137983 次 |
| 最近记录: |