0

I'm wondering why this doesn't work (on Chrome version 87.)

<html>
<body>
<button onclick="getTextContent()">Get textContent</button>
<p>Hello</p>
<script>
function getTextContent() {
    alert(document.querySelector("p[textContent*='Hello']").textContent)
}
</script>
</body>
</html>

I thought tapping the button would alert with "Hello" but it does nothing.

Joe Smith
  • 1,900
  • 1
  • 16
  • 15
  • 2
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+css+selector+for+text+content) of [Is there a CSS selector for elements containing certain text?](https://stackoverflow.com/q/1520429/4642212). There is no such way with CSS selectors, and it’s unlikely that one will ever be added. Use `console.log(Array.from(document.querySelectorAll("p")).find(({textContent}) => textContent.includes("Hello")).textContent);` instead. ([Use `console.log` instead of `alert`](https://stackoverflow.com/q/8203473/4642212)). – Sebastian Simon Dec 29 '20 at 23:18
  • 1
    Short answer is .. No. You would need to loop through a collection and find a match(es) yourself – charlietfl Dec 29 '20 at 23:20
  • 1
    You could make your own thing like this by collecting all of the p tags as an array, and then using filter to find one or multiple that either exactly have the text you want or you could set it up for just including that somewhere in the string of the textContent – Samathingamajig Dec 29 '20 at 23:22
  • 1
    https://github.com/jquery/jquery/blob/master/src/selector.js#L858 For reference to how jQuery implements their pseudoselector `:contains` – Taplar Dec 29 '20 at 23:36

0 Answers0