Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need jQuery code to append parameters to all urls contained in a div

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.

like image 590
Ali Avatar asked Dec 17 '22 23:12

Ali


1 Answers

$('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");
like image 63
Pointy Avatar answered Apr 27 '23 01:04

Pointy