如何通过innerText获取元素

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)

  • 不,这个问题是关于JavaScript和HTML,而不是Java (5认同)
  • 我发现如果你有 &lt;span&gt;&lt;span&gt;search text&lt;/span&gt;&lt;/span&gt; 这个方法可能会返回外部跨度而不是内部跨度。 (2认同)

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)

  • 这应该是最好的答案.XPath可以做更多的事情,比如按属性值选择节点,选择节点集......简单介绍:https://www.w3schools.com/xml/xpath_syntax.asp (2认同)
  • 简单,优雅和高级。最佳答案。 (2认同)
  • 问题是,这个诡计的性能损失是什么 (2认同)
  • @vsync我认为这比任何其他答案都要快,因为xpath是由浏览器提供的算法执行的,而不是像所有其他答案一样在javascript中执行.这是一个有趣的问题. (2认同)
  • @Daniel您需要将调用更改为: ```js varmatchingElementSet = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while(element = result.iterateNext()) { // 对每个元素执行一些操作 } ``` https://developer.mozilla.org/en-US/docs/Web/API/XPathResult/iterateNext (2认同)
  • @Raiyan 在我的示例中使用 * 而不是 'a' 来匹配所有标签 (2认同)

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)

当然,传统浏览器不会处理此问题,但如果需要传统支持,您可以使用转换器.

  • 比为 xpath 学习新的解析语言要好得多,并且更容易迭代。 (5认同)

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)

参考文献:


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


Cyb*_*tic 9

只需将您的子字符串传递到以下行:

外部 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)

在此处输入图片说明

  • 这会返回 true 或 false,但不返回元素。 (3认同)

小智 9

你可以这样做,不确定是否推荐这样做,但它对我有用。

[... document.querySelectorAll('a')].filter(el => el.textContent.includes('sometext'));
Run Code Online (Sandbox Code Playgroud)

  • 通过额外的支持信息可以改进您的答案。请[编辑]添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以[在帮助中心](/help/how-to-answer)找到有关如何写出好的答案的更多信息。 (2认同)

小智 6

document.querySelectorAll('a').forEach(function (item) {
    if (item.innerText == 'SearchingText') {
        console.dir(item);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 请不要发布仅代码的答案,而是添加一些文字解释,说明您的方法如何以及为何有效,以及它与给出的其他答案有何不同。您还可以查看我们的[“如何写出好的答案”](https://stackoverflow.com/help/how-to-answer)条目。 (2认同)

Ami*_*IRI 5

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)

JSfiddle.net


Ori*_*ori 5

您可以使用 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)


Alk*_*kie 5

如果需要,从在 <=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)

  • 我喜欢这个方法。您还可以使用“Array.from”代替“[].slice.call”。例如:`Array.from(document.querySelectorAll('a'))` (2认同)