Oskar Szura
Oskar Szura

Reputation: 2549

Selecting element by a content text

Is there a simple way (I mena only by a selector) to select element that has some specific 'content text'?.

For example, we can have the following situation

<div>
 <div class="a">text 1</div>
 <div class="a">text 2</div>
 <div class="a">text 3</div>
</div>

we can do something like

$('div div.a').each(function() {
    if( ($this).text() == "text 1") {
       // do something
    }
});

but is there a way we can do something like:

 $('div div.a[text="text 1"])

or

 $('div div.a').someEMBEDEDfunction('text 1')

?

Upvotes: 0

Views: 54

Answers (2)

Claudio Redi
Claudio Redi

Reputation: 68400

Use contains

$('div div.a:contains("text 1"))

Something to take into account is that this selector is case sensitive. If you need a case insensitive version, you'll need to implement your own selector or override existing one.

Upvotes: 6

DevlshOne
DevlshOne

Reputation: 8457

There is also a much more complex answer that involves the .contents() method, nodeTypes and innerHTML. I like Claudio's much better!

Upvotes: 0

Related Questions