jqueryfunctionclickcontains

how to check if a link was clicked?


Here is my problem. I am editing a website that is generating all the content of the website in a loop from the server side to the PHP and then I am asked to manipulate the website using jQuery.

The question here is that, a lot of link tags that exists on the website have no IDs associcated with them. So I am asked to solve a problem, where if one of the link tags is clicked, some jQuery logic takes place.

In my case, if link tag with text "See All" is clicked. I am supposed to carry out some code execution but how exactly do I write it?

Is it as simple as writing:

$("a:contains('See All')").click(function() {
  // do something
});

because that doesn't seem to be working. Any help?


Solution

  • Exact matching for See All and so on

    $("a")
         .filter(function() {   // apply filter() to for exact text matching
              return $(this).text() == 'See All';
         }).click(function(e) {
              // To prevent page reload you need .preventDefault()
              e.preventDefault();
              alert('hello');
         });
    

    DEMO

    Check containment of See All (not exact match)

    $("a").filter(function() {
        return $(this).text().match('See All'); // a little change here
    }).click(function() {
        alert('hello');
    });
    

    or just use :contains()

    $('a:contains(See All)').on('click', function() {
       alert('Hello');
    });
    

    DEMO

    Some extra note

    If your links generate after DOM ready then you need to try with ".on" event binding like:

    $('#container').on('click', 'a:contains(See All)', function() {
      alert('Hello');
    });
    

    and in case the client was using jQuery v-1.7, then try ".delegate" event as follows:

    $('#container').delegate('a:contains(See All)', 'click', function() {
      alert('Hello');
    });