开发者

Getting all links with specific inner HTML value in jQuery

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

I want to select all anchor elements that have text=text2. I'm looking for something like this:

$('a[text=Text2]')

Edit: Why this is not working? For some some reason, it needs to be in this format:

开发者_StackOverflow社区
$('div').find('a').find(':contains("Text2")')


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


You're looking for contains:

$("a:contains('text2')")


Use the :contains() filter.

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


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜