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

};
4
  • 1
    jQuery? stackoverflow.com/questions/7896455/… Commented Apr 8, 2017 at 15:11
  • 1
    what exactly are you trying to accomplish? Don't use regex to parse html Commented Apr 8, 2017 at 15:14
  • 3
    @mplungjan Question has no jQuery tag. Commented Apr 8, 2017 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 Commented Apr 8, 2017 at 16:14

2 Answers 2

14

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>

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.