I need a jQuery code snippet which appends the parameter action=xyz
to all urls within a page - note it should also check that if the urls already have other parameters appended or not: e.g., for a url such as index.php?i=1
it should append &action=xyz
and for urls without parameters like index.php
it should append ?action=xyz
.
Asked
Active
Viewed 3,686 times
4

Marcel Korpel
- 21,536
- 6
- 60
- 80

Ali
- 7,353
- 20
- 103
- 161
1 Answers
12
$('a').each(function() {
this.href += (/\?/.test(this.href) ? '&' : '?') + 'action=xyz';
});
That finds all the <a>
tags and updates their "href" value as you described. You could turn it into a jQuery plugin if you need to pass different "xyz" values:
jQuery.fn.addAction = function(action) {
return this.each(function() {
if ($(this).is('a')) {
this.href += (/\?/.test(this.href) ? '&' : '?') + 'action=' + escapeURLComponent(action);
}
};
}
Then you could just do $('a').addAction("xyz");
or, in your case,
$('#yourDiv a').addAction("xyz");

Pointy
- 405,095
- 59
- 585
- 614