turnt
turnt

Reputation: 3255

Select element based on the content within

Suppose I have html like this:

<a href='#'>Apple</a>
<a href='#'>Orange</a>
<a href='#'>Apple</a>

How would I select only the links that say have the content of Apple within?

Upvotes: 2

Views: 45

Answers (3)

Magicprog.fr
Magicprog.fr

Reputation: 4100

Select the content with the :contains jquery selector:

HTML:

<a href='#'>Apple</a>
<a href='#'>Orange</a>
<a href='#'>Apple</a>

JQUERY:

$('a:contains("Apple")').css("color","red");

Don't forget to include the Jquery library if you didn't include it before:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JSFIDDLE: http://jsfiddle.net/ghorg12110/p1x3n43s/

Upvotes: 0

Andr&#233;s Torres
Andr&#233;s Torres

Reputation: 733

Using the Jquery's filter method http://api.jquery.com/filter/

var Apples = $('a').filter(function () {
  return $.trim($(this).text()) == 'Apple';
});

Upvotes: 0

Alex Char
Alex Char

Reputation: 33218

You can use :contains()

$("a:contains('Apple')").addClass("apple");
.apple {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#'>Apple</a>
<a href='#'>Orange</a>
<a href='#'>Apple</a>

Upvotes: 5

Related Questions