2

How can use :contains to find the object has a certain keyword when it is clicked?

<a href="#" class="click">&#187; Read More</a>

$('.click').click(function() {

   if($(":contains('More')", this)) alert('1');

});

I get the alert whenever it contains the keyword or not... how can I make it?

Run
  • 54,938
  • 169
  • 450
  • 748

4 Answers4

2

You need to use is to see if an element matches your :contains selector:

$(".click").click(function () {
    if ($(this).is(":contains('More')")) {
        alert('1');
    }
});

Example: http://jsfiddle.net/3N8ek/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
1

Try this:

$(".click:contains('More')").click(function() {

   alert('1');

});
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • thanks but I need to find the keyword after the click event - not when the click even happens. is it possible? – Run Aug 31 '11 at 18:52
1

You are always getting alert because you are not checking for length property of jQuery object. jQuery always returns at least an empty object when it do not find any match. So if($(":contains('More')", this)) will always return true no matter what.

$('.click').click(function() {

   if ($(this).is(":contains('More')")) {
     alert('1');
   }

});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • @ShankarSangoli: This will not work. Your selector means "find all elements that contain "More" underneath the clicked element). – Andrew Whitaker Aug 31 '11 at 18:50
0

This should work:

if($(this + ':contains("More")')) alert('1');

See :contains-docs for more on the usage.

Sgoettschkes
  • 13,141
  • 5
  • 60
  • 78