Javascript 如何通过innerText获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3813294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:15:14  来源:igfitidea点击:

How to get element by innerText

javascriptjqueryinnertext

提问by Anton Kandybo

How to get tag in html page, if I know what text tag contains. E.g.:

如果我知道文本标签包含什么,如何在 html 页面中获取标签。例如:

<a ...>SearchingText</a>

采纳答案by August Lilleaas

You'll have to traverse by hand.

你必须手动穿越。

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`.

回答by carlin.scott

You could use xpath to accomplish this

您可以使用 xpath 来完成此操作

var xpath = "//a[text()='SearchingText']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

You can also search of an element containing some text using this xpath:

您还可以使用此 xpath 搜索包含某些文本的元素:

var xpath = "//a[contains(text(),'Searching')]";

回答by Mouneer

You can use jQuery :contains() Selector

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

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

回答by Mouneer

Using the most modern syntax available at the moment, it can be done very cleanly like this:

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

for (const a of document.querySelectorAll("a")) {
  if (a.textContent.includes("your search term")) {
    console.log(a.textContent)
  }
}

Or with a separate filter:

或者使用单独的过滤器:

[...document.querySelectorAll("a")]
   .filter(a => a.textContent.includes("your search term"))
   .forEach(a => console.log(a.textContent))

Naturally, legacy browsers won't handle this, but you can use a transpiler if legacy support is needed.

自然,旧版浏览器不会处理这个问题,但如果需要旧版支持,您可以使用转译器。

回答by David says reinstate Monica

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

Of course, a somewhat simpler way still is:

当然,更简单的方法仍然是:

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

References:

参考:

回答by Pawel

Functional approach. Returns array of all matched elements and trims spaces around while checking.

功能方法。返回所有匹配元素的数组并在检查时修剪周围的空格。

function getElementsByText(str, tag = 'a') {
  return Array.prototype.slice.call(document.getElementsByTagName(tag)).filter(el => el.textContent.trim() === str.trim());
}

Usage

用法

getElementsByText('Text here'); // second parameter is optional tag (default "a")

if you're looking through different tags i.e. span or button

如果您正在查看不同的标签,即跨度或按钮

getElementsByText('Text here', 'span');
getElementsByText('Text here', 'button');

The default value tag = 'a' will need Babel for old browsers

默认值 tag = 'a' 旧浏览器需要 Babel

回答by Cybernetic

Simply pass your substringinto the following line:

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

Outer HTML

外部 HTML

document.documentElement.outerHTML.includes('substring')

Inner HTML

内部 HTML

document.documentElement.innerHTML.includes('substring')

You can use these to search through the entire documentand retrieve the tags that contain your search term:

您可以使用这些来搜索整个文档并检索包含搜索词的标签:

function get_elements_by_inner(word) {
    res = []
    elems = [...document.getElementsByTagName('a')];
    elems.forEach((elem) => { 
        if(elem.outerHTML.includes(word)) {
            res.push(elem)
        }
    })
    return(res)
}

Usage:

用法

How many times is the user "T3rm1" mentioned on this page?

用户“T3rm1”在本页提及多少次?

get_elements_by_inner("T3rm1").length

1

1

How many times is jQuery mentioned?

jQuery 被提及多少次?

get_elements_by_inner("jQuery").length

3

3

Get all elements containing the word "Cybernetic":

获取所有包含“控制论”一词的元素:

get_elements_by_inner("Cybernetic")

enter image description here

在此处输入图片说明

回答by Amin NAIRI

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]

JSfiddle.net

JSfiddle.net

回答by Zack Marrapese

While it's possible to get by the inner text, I think you are heading the wrong way. Is that inner string dynamically generated? If so, you can give the tag a class or -- better yet -- ID when the text goes in there. If it's static, then it's even easier.

虽然可以通过内部文本获得,但我认为您走错了路。那个内部字符串是动态生成的吗?如果是这样,您可以为标签指定一个类或——更好——当文本进入时的 ID。如果它是静态的,那就更容易了。

回答by Alkie

To get the filter method from user1106925working in <=IE11 if needed

如果需要,从在 <=IE11 中工作的user1106925获取过滤器方法

You can replace the spread operator with:

您可以将扩展运算符替换为:

[].slice.call(document.querySelectorAll("a"))

[].slice.call(document.querySelectorAll("a"))

and the includes call with a.textContent.match("your search term")

和包括调用 a.textContent.match("your search term")

which works pretty neatly:

它工作得非常整洁:

[].slice.call(document.querySelectorAll("a"))
   .filter(a => a.textContent.match("your search term"))
   .forEach(a => console.log(a.textContent))