如何通过innerText获取元素

时间:2010-09-28 13:39:14

标签: javascript jquery innertext

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

<a ...>SearchingText</a>

15 个答案:

答案 0 :(得分:102)

你必须手动遍历。

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

答案 1 :(得分:92)

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

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

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

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

答案 2 :(得分:27)

您可以使用jQuery :contains() Selector

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

答案 3 :(得分:25)

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

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

当然,传统浏览器无法处理此问题,但如果需要传统支持,则可以使用转换器。

答案 4 :(得分:13)

虽然已经有一段时间了,而且你已经(很久以来)接受了答案,我想我会提供更新的方法:

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>

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

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>

参考文献:

答案 5 :(得分:12)

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

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

用法

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

如果你正在浏览不同的标签,例如span或button

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

默认值标记=&#39; a&#39;旧浏览器需要使用Babel

答案 6 :(得分:4)

与其他答案相比,我发现使用较新的语法要短一些。所以这是我的建议:

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

答案 7 :(得分:3)

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

答案 8 :(得分:1)

虽然有可能通过内部文本,我认为你走错了路。是否动态生成内部字符串?如果是这样,你可以给标签一个类或者 - 更好的 - 当文本进入那里时的ID。如果它是静态的,那就更容易了。

答案 9 :(得分:0)

我认为你需要更具体一点来帮助我们。

  1. 你是怎么发现这个的? JavaScript的? PHP? Perl的?
  2. 您可以将ID属性应用于代码吗?
  3. 如果文本是唯一的(或者实际上,如果不是,但你必须通过数组运行),你可以运行一个正则表达式来找到它。使用PHP的preg_match()可以解决这个问题。

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

答案 10 :(得分:0)

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

外部HTML

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

内部HTML

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

答案 11 :(得分:0)

您可以使用TreeWalker遍历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);
<a ...>SearchingText</a>

答案 12 :(得分:0)

这可以完成工作。
返回包含text的节点数组。

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

答案 13 :(得分:-1)

我只需要一种方法来获取包含特定文本的元素,这就是我想出来的。

使用document.getElementsByInnerText()获取多个元素(多个元素可能具有相同的确切文本),并使用document.getElementByInnerText()只获取一个元素(第一个匹配)。

此外,您可以使用元素(例如someElement.getElementByInnerText())代替document来本地化搜索。

您可能需要调整它以使其跨浏览器或满足您的需求。

我认为代码是不言自明的,所以我会保持原样。

HTMLElement.prototype.getElementsByInnerText = function (text, escape) {
    var nodes  = this.querySelectorAll("*");
    var matches = [];
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].innerText == text) {
            matches.push(nodes[i]);
        }
    }
    if (escape) {
        return matches;
    }
    var result = [];
    for (var i = 0; i < matches.length; i++) {
        var filter = matches[i].getElementsByInnerText(text, true);
        if (filter.length == 0) {
            result.push(matches[i]);
        }
    }
    return result;
};
document.getElementsByInnerText = HTMLElement.prototype.getElementsByInnerText;

HTMLElement.prototype.getElementByInnerText = function (text) {
    var result = this.getElementsByInnerText(text);
    if (result.length == 0) return null;
    return result[0];
}
document.getElementByInnerText = HTMLElement.prototype.getElementByInnerText;

console.log(document.getElementsByInnerText("Text1"));
console.log(document.getElementsByInnerText("Text2"));
console.log(document.getElementsByInnerText("Text4"));
console.log(document.getElementsByInnerText("Text6"));

console.log(document.getElementByInnerText("Text1"));
console.log(document.getElementByInnerText("Text2"));
console.log(document.getElementByInnerText("Text4"));
console.log(document.getElementByInnerText("Text6"));
<table>
    <tr>
        <td>Text1</td>
    </tr>
    <tr>
        <td>Text2</td>
    </tr>
    <tr>
        <td>
            <a href="#">Text2</a>
        </td>
    </tr>
    <tr>
        <td>
            <a href="#"><span>Text3</span></a>
        </td>
    </tr>
    <tr>
        <td>
            <a href="#">Special <span>Text4</span></a>
        </td>
    </tr>
    <tr>
        <td>
            Text5
            <a href="#">Text6</a>
            Text7
        </td>
    </tr>
</table>

答案 14 :(得分:-2)

jQuery版本:


$('a').each(function(i) {
    var $element = $(this)[i];

    if( $element.text() == 'Your Text' ) {
        /** Do Something */
    }
});

相关问题