How can use :contains() Selector to determine the object has a certain keyword when it is clicked?

StackOverflow https://stackoverflow.com/questions/7261797

  •  17-01-2021
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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/

OTHER TIPS

Try this:

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

   alert('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');
   }

});

This should work:

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

See :contains-docs for more on the usage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top