我如何能找到DIV与某些文本?例如:

<div>
SomeText, text continues.
</div>

试图使用这样的东西:

var text = document.querySelector('div[SomeText*]').innerTEXT;
alert(text);

当然,这是行不通的。我该怎么做呢?


当前回答

在2021年遇到这个问题时,我发现使用XPATH太复杂了(需要学习其他东西),不适合做一些应该相当简单的事情。

我想到了这个:

function querySelectorIncludesText (selector, text){
  return Array.from(document.querySelectorAll(selector))
    .find(el => el.textContent.includes(text));
}

用法:

querySelectorIncludesText('button', 'Send')

请注意,我决定使用包含,而不是严格的比较,因为这是我真正需要的,请随意调整。

如果你想支持所有浏览器,你可能需要这些腻子:

  /**
   * String.prototype.includes() polyfill
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
   * @see https://vanillajstoolkit.com/polyfills/stringincludes/
   */
  if (!String.prototype.includes) {
    String.prototype.includes = function (search, start) {
      'use strict';

      if (search instanceof RegExp) {
        throw TypeError('first argument must not be a RegExp');
      }
      if (start === undefined) {
        start = 0;
      }
      return this.indexOf(search, start) !== -1;
    };
  }

其他回答

我也有类似的问题。

函数返回包含arg文本的所有元素。

这对我来说很管用:

function getElementsByText(document, str, tag = '*') {
return [...document.querySelectorAll(tag)]
    .filter(
        el => (el.text && el.text.includes(str))
            || (el.children.length === 0 && el.outerText && el.outerText.includes(str)))

}

由于数据属性中的文本长度没有限制,所以请使用数据属性!然后你可以使用常规的css选择器来选择你的元素(s)像OP想要的。

for (document.querySelectorAll("*")的常量元素){ element.dataset.myInnerText = element.innerText; } 文档。querySelector(“* [data-my-inner-text = '不同的文本。']”).style.color =“蓝色”; <div> . SomeText, text continue .</div> . SomeText, text continue 不同文本< div >。< / div >

理想情况下,您可以在文档加载时完成数据属性设置部分,并缩小querySelectorAll选择器的范围以提高性能。

我一直在寻找一种使用Regex来做类似事情的方法,并决定构建我自己的东西,如果其他人正在寻找类似的解决方案,我想分享它。

function getElementsByTextContent(tag, regex) {
  const results = Array.from(document.querySelectorAll(tag))
        .reduce((acc, el) => {
          if (el.textContent && el.textContent.match(regex) !== null) {
            acc.push(el);
          }
          return acc;
        }, []);
  return results;
}

OP的问题是关于纯JavaScript而不是jQuery。 虽然有很多答案,我喜欢@Pawan Nogariya的答案,但请看看这个替代答案。

你可以在JavaScript中使用XPATH。更多关于MDN文章的信息请点击这里。

document.evaluate()方法对XPATH查询/表达式求值。因此,您可以在那里传递XPATH表达式,遍历HTML文档并找到所需的元素。

在XPATH中,您可以通过如下所示的文本节点选择一个元素,它将获得具有以下文本节点的div。

//div[text()="Hello World"]

要获得一个包含一些文本的元素,使用以下方法:

//div[contains(., 'Hello')]

XPATH中的contains()方法将节点作为第一个参数,将要搜索的文本作为第二个参数。

看这里,这是JavaScript中XPATH的例子

下面是一个代码片段:

var headings = document.evaluate("//h1[contains(., 'Hello')]", document, null, XPathResult.ANY_TYPE, null );
var thisHeading = headings.iterateNext();

console.log(thisHeading); // Prints the html element in console
console.log(thisHeading.textContent); // prints the text content in console

thisHeading.innerHTML += "<br />Modified contents";  

如您所见,我可以获取HTML元素并按我喜欢的方式修改它。

在2021年遇到这个问题时,我发现使用XPATH太复杂了(需要学习其他东西),不适合做一些应该相当简单的事情。

我想到了这个:

function querySelectorIncludesText (selector, text){
  return Array.from(document.querySelectorAll(selector))
    .find(el => el.textContent.includes(text));
}

用法:

querySelectorIncludesText('button', 'Send')

请注意,我决定使用包含,而不是严格的比较,因为这是我真正需要的,请随意调整。

如果你想支持所有浏览器,你可能需要这些腻子:

  /**
   * String.prototype.includes() polyfill
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
   * @see https://vanillajstoolkit.com/polyfills/stringincludes/
   */
  if (!String.prototype.includes) {
    String.prototype.includes = function (search, start) {
      'use strict';

      if (search instanceof RegExp) {
        throw TypeError('first argument must not be a RegExp');
      }
      if (start === undefined) {
        start = 0;
      }
      return this.indexOf(search, start) !== -1;
    };
  }