6

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

};
millk
  • 63
  • 1
  • 3
  • 1
    jQuery? http://stackoverflow.com/questions/7896455/jquery-selector-for-an-element-that-directly-contains-text – mplungjan Apr 08 '17 at 15:11
  • 1
    what exactly are you trying to accomplish? [Don't use regex to parse html](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – charlietfl Apr 08 '17 at 15:14
  • 3
    @mplungjan Question has no jQuery tag. – kind user Apr 08 '17 at 15:17
  • @Kinduser - hence my question and not hammer closing - new SO user could still want a solution that involved jQuery without tagging it – mplungjan Apr 08 '17 at 16:14

2 Answers2

13

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>
kind user
  • 40,029
  • 7
  • 67
  • 77
0

With pure Javascript just grab element's parent like this:

var x = this.parentElement.nodeName; //x=="span"

or

var x = this.parentElement; //x == <span> object

With jQuery just grab element's parent like this:

$(this).parents("span");

So if you add above line inside your if you can get span element as object or as text.

Konstantinos
  • 943
  • 1
  • 9
  • 20