首页 > 解决方案 > 根据文本获取 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);
        });

提前致谢!

标签: javascriptjquery

解决方案


在 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);
}

推荐阅读