Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the DOM element with specific text in javascript

Tags:

javascript

dom

I know how to find specific text, but I'm really struggling to find elements with specific text for example: <span class="foo">Special</span>

Is there example like this script below to find elemements with text?

var txt = window.document.body.innerHTML;
if (txt.match(/Special/)) {
    // do something if true
    alert("Found");
} else {
    // do something if false
    alert("Sorry");

};
like image 966
millk Avatar asked Aug 31 '26 13:08

millk


1 Answers

You could e.g. catch every element inside your document and check if any of them contains given text.

var elems = document.querySelectorAll("*"),
    res = Array.from(elems).find(v => v.textContent == 'Special');
    
    console.log(res ? 'found!' : 'not found');
<span class="foo">Special</span>
<span class="foo">Else</span>
like image 57
kind user Avatar answered Sep 03 '26 04:09

kind user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!