javascript - 根据文本获取 div 元素
问题描述
我有下面的代码。我想检索包含以下文本的元素。我不知道文本在哪个 div 中,所以必须搜索整个页面。
$('*', 'body')
.addBack()
.contents()
.filter(function(){
return this.nodeType === 3;
})
.filter(function(){
// Text below: {launch=[MODULE]}
return this.nodeValue.indexOf('{launch=[MODULE]}') != -1;
})
.each(function(){
// How do I receive the element here?
console.log(this);
});
提前致谢!
解决方案
在 javascript 中,您可以收集所有<div>
元素,然后循环遍历它们textContent
,每次都检查属性。
例子:
// GRAB ALL THE DIVS
const allDivs = [...document.getElementsByTagName('div')];
// SET THE SEARCH PHRASE
const searchPhrase = '{launch=[MODULE]}';
// LOOP THROUGH ALL THE DIVS, LOOKING FOR THE SEARCH PHRASE
for (let div of allDivs) {
if (div.textContent !== searchPhrase) continue;
console.log(div);
}
推荐阅读
- r - How to extract all words after the nth word from string in R?
- python - Python中map函数的行为
- android - 如何将所有按钮设置为无边框 Android
- python - Python 或 bash 脚本:如果模式在两个相同标记之间的行中,则删除行和第一个标记
- iphone - Swift 工具栏按钮仅在一个场景中触发 exec_bad_instruction
- android - Handling Entities and Pojos
- r - 从 R 函数生成 .md 降价文件
- go - Vault Token Helper not being detected?
- php - 未定义的偏移量#####
- android - 等待蓝牙启用