1

Somehow I would like to search directly for some text? Is that possible using querySelector?

Dom :

<div class="div1">
    <span class="text">
        <span> text to search </span>
    </span>
</div>



I have tried the following without success.

JS Code: document.querySelector('div[contains("text to")]') = FAIL

I know the easy way something like: document.querySelector('span.text > span')
My example is kept simple, I know that. I am looking for a solution similar to selenium selenium driver.find_element_by_link_text

I want to independently search for an element without relying on the class or id, any ideas?

Lisa_sh
  • 41
  • 6
  • Does this answer your question? [Is there a CSS selector for elements containing certain text?](https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text) – jeprubio May 05 '20 at 00:56
  • This didn't answer my question, but it was very helpfully. Thanks (= – Lisa_sh May 05 '20 at 08:03

1 Answers1

1

It is not possible with querySelector directly. You have to fetch all spans first and then iterate over them to see which one has the text you want. For example:

var results = []; 
document.querySelector("span").forEach(elem => {
    if (elem.textContent.includes("text to")) {
        results.push(elem);
    }
});
Alejandro De Cicco
  • 1,216
  • 3
  • 17
  • thanks for the answer, so i had a similar result, but i was on hopinig there is simple alternative. (= – Lisa_sh May 05 '20 at 08:07