Reputation: 49
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 ID
s 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?
Upvotes: 2
Views: 8516
Reputation: 1
How about using a link shortening service (e.g. Google's https://goo.gl/, or click to tweet's clicktotweet.com, free for 5 and paid there after). The use the shortened link.
This will keep track of the number of times the link is clicked.
Now what you were looking for, no
Upvotes: 0
Reputation: 87073
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');
});
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');
});
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');
});
Upvotes: 4
Reputation: 60516
Have you tried removing the '
in 'See All'
?
Also, to make sure that it doesn't redirect the users to the link in href
, use e.preventDefault()
$("a:contains(See All)").click(function(e) {
e.preventDefault();
// do something
});
Upvotes: 1