millk
millk

Reputation: 63

Finding the DOM element with specific text in javascript

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

};

Upvotes: 6

Views: 8537

Answers (2)

Konstantinos
Konstantinos

Reputation: 973

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.

Upvotes: 0

kind user
kind user

Reputation: 41893

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>

Upvotes: 14

Related Questions