如何获得标签在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())
    );
  }

其他回答

我想你需要说得更具体一点,我们才能帮到你。

你是怎么发现的?Javascript ?PHP吗?Perl吗? 您可以将ID属性应用于标记吗?

如果文本是唯一的(或者实际上不是唯一的,但必须通过数组运行),则可以运行正则表达式来找到它。使用PHP的preg_match()可以解决这个问题。

如果你正在使用Javascript并且可以插入ID属性,那么你可以使用getElementById(' ID ')。然后可以通过DOM: https://developer.mozilla.org/en/DOM/element.1访问返回元素的属性。

你可以使用jQuery:contains()选择器

var element = $( "a:contains('SearchingText')" );

使用目前最现代的语法,它可以像这样非常干净地完成:

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

你可以这样做,不确定这是否被推荐,但对我来说很有效。

[... document.querySelectorAll('a')].filter(el => el.textContent.includes('sometext'));