Getting all links with specific inner HTML value i

2019-03-14 11:06发布

<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:

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

4条回答
Juvenile、少年°
2楼-- · 2019-03-14 11:27

You're looking for contains:

$("a:contains('text2')")
查看更多
家丑人穷心不美
3楼-- · 2019-03-14 11:28
甜甜的少女心
4楼-- · 2019-03-14 11:38

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")');
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-03-14 11:42

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

查看更多
登录 后发表回答