views:

482

answers:

4
<div>
    <a>
       Text1
       <img alt="" stc="" />
    </a>
    <a>
       Text2
    </a>
 </div>

I want to select all a elements that have text=text2. I looking for something like that:

$('a[text=Text2]')




Edit: Why this is not working? (from some reasons it's need to be in this format).

$('div').find('a').find(':contains("Text2")')
+2  A: 

Use the :contains() filter.

http://api.jquery.com/contains-selector/

Chetan Sastry
+3  A: 

You're looking for contains:

$("a:contains('text2')")
Kevin Gorski
I updated the question.
Mendy
A: 

As an additional note, rather than scanning for exact text inside a link it might be better to be scanning for attributes, e.g.

<div class="farm-market-items">
  <a class="market-item" data-item-type="seed" data-item-id="817">
    Carrot Seed
    <img alt="" src="" class="item-thumb" />
  </a>
  <a class="market-item" data-item-type="seed" data-item-id="25">
    Spinach Seed
  </a>
  <a class="market-item" data-item-type="tree" data-item-id="981">
    Pear Tree
  </a>
</div>

Now you can (accurately) scan for:

all_seeds = $('a[data-item-type="seed"]');

(I'm a big fan of the data-* attributes.)

Amy
From some reason it's need to be in the above format. So I must query it only from the innerText.
Mendy
+5  A: 

You ask why this doesn't work:

$('div').find('a').find(':contains("Text2")')

The reason is, .find() will search children elements, you want .filter() (because you already selected the a - or you add the :contains to the a find:

$('div').find('a').filter(':contains("Text2")');
$('div').find('a:contains("Text2")');
gnarf
Forgot about `.filter()`. Thanks.
Mendy
I wonder why you didn't change the initial selector to $('div a:contains("Text2")') instead of the Find/Filter chain? jQuery selectors traverse descendants just like CSS selectors do.
Kevin Gorski
@kevin because of the comment in the op: 'from some reasons it's need to be in this format'
gnarf