I have a set of links on my page and some of them start with /mypath, like this <a href="/mypath/other/stuff">

I need to add a querystring to the links that start this way, so the result is something like <a href="/mypath/other/stuff?parent=1234"> with the '1234' being the node id of the node we're currently viewing.

I've sucessfully passed the nid into my js file using drupal settings. The only part of this I can't get to work is putting the original link in where you see the second attr('href').

My code is as follows:

    $('a[href^="/mypath/"]').attr('href', attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid);

Instead of that second attr('href') I've tried a number of things and can't figure out what it should be.

  • Is the problem with the selector or with the href value? Is it changing the href at all with what you've got here? Commented Jun 22, 2012 at 17:16
  • If I put a static url (ie. 'google.com') in there instead of the attr('href') it works as expected. Right now, due to it just erroring, it returns the original url)
    – Feature
    Commented Jun 22, 2012 at 17:19

1 Answer 1


You've got nothing to hook onto for that second attr() as you're not storing the result of the jQuery call in a variable.

I'd advise using a loop instead:

$('a[href^="/mypath/"]').each(function(index, element) {
  var newAttr = $(element).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(element).attr('href', newAttr);

That will catch any link on the page that matches the path selector.

  • Awesome, thanks! I figured it had something to do with the href not being defined. The only thing I don't get about this is what's the 'index, element' part?
    – Feature
    Commented Jun 22, 2012 at 17:26
  • No worries :) Those variables are provided by the each() function, I think the docs page can do a better job of explaining than I can
    – Clive
    Commented Jun 22, 2012 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.