質問

テキストタグにどのようなものが含まれているかがわかっている場合、HTMLページのタグを取得する方法。例えば。:

<a ...>SearchingText</a>
役に立ちましたか?

解決

あなたが手でトラバースする必要があります。

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

他のヒント

この

を達成するために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')]";

あなたが使用できるjQueryの:含まれています()セレクタ

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

当然のことながら、レガシーブラウザはこれを処理しませんが、レガシーサポートが必要な場合は、transpilerを使用することができます。

かなりの時間が経ち、あなたはすでに(ずっと前から)回答を受け入れていますが、私は最新のアプローチを提供したいと考えました。

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>

参考文献:

機能的なアプローチ。確認しながら、周りのすべてのマッチした要素とトリムスペースの配列を返します。

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

は異なるタグを通じて探しているなら、すなわちスパンまたはボタン

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

デフォルト値タグ=「」

古いブラウザ用のバベルが必要になります

私は他の人の答えに比べて、より新しい構文の使用は少し短い発見しました。だからここに私の提案だ。

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する

単にあなたのものを渡すだけです 部分文字列 次の行に追加します。

外側のHTML

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

内部HTML

document.documentElement.innerHTML.includes('substring')
それは内部テキストで取得することも可能ですが、

は、私はあなたが間違った方向に向かっていると思います。その内側の文字列は動的に生成されていますか?テキストがそこに行くときID - いっそのこと - もしそうなら、あなたはタグにクラスまたはを与えることができます。それの静的な場合、それはさらに簡単です。

私たちがサポートするには、もう少し具体的にする必要があると思います。

  1. どうやってこれを見つけたのですか?ジャバスクリプト?PHP?パール?
  2. タグに ID 属性を適用できますか?

テキストが一意である場合 (実際には一意ではないが、配列を実行する必要がある場合)、正規表現を実行してテキストを見つけることができます。PHP の preg_match() を使用すると機能します。

Javascript を使用していて ID 属性を挿入できる場合は、getElementById('id') を使用できます。その後、DOM を通じて返された要素の属性にアクセスできます。 https://developer.mozilla.org/en/DOM/element.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>

jQueryのバージョン:

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

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top