Reputation: 51
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?
Upvotes: 2
Views: 2552
Reputation: 1236
It is not possible with querySelector
directly. You have to fetch all spans with querySelectorAll
first and then iterate over them to see which one has the text you want. For example:
var results = [];
document.querySelectorAll("span").forEach(elem => {
if (elem.textContent.includes("text to")) {
results.push(elem);
}
});
Upvotes: 1