Tim Tim - 1 year ago 72
Javascript Question

Rewriting href in vanilla JS for all <a> objects that begin with a specific ID

I'm trying to append a parameter to the URLs of a number of items in a menu using vanilla JS (no jQuery etc).

All of the menu items that I want to play with have one thing in common and I assume this is key to selecting the right objects: They all begin with the same ID.

So what I have looks like this:

<a href="someplace.php" id="actionMenu123">Link 1</a>
<a href="someplace2.php" id="actionMenu456">Link 2</a>
<a href="someplace3.php" id="actionMenu789">Link 3</a>
<a href="someplace4.php" id="actionMenuABV">Link 4</a>
<a href="someplace5.php" id="actionMenu5X4">Link 5</a>

And the JS script that I need should result in the following:

<a href="someplace.php?John=Doe" id="actionMenu123">Link 1</a>
<a href="someplace2.php?John=Doe" id="actionMenu456">Link 2</a>
<a href="someplace3.php?John=Doe" id="actionMenu789">Link 3</a>
<a href="someplace4.php?John=Doe" id="actionMenuABV">Link 4</a>
<a href="someplace5.php?John=Doe" id="actionMenu5X4">Link 5</a>

I tried to rewrite the hrefs by selecting all objects that contain "actionMenu" in their DOM by using querySelectorAll but I don't think I'm doing it right.

I'd be grateful for any pointers.

Thank you!

Answer Source
// first, get list of all 'a' tags and convert to array

  // filter for ones whose id matches. We also want to make
  // sure it *has* an id and an href
  .filter(node => node.id && node.href && node.id.match(/^actionmenu/i))

  // rewrite the href
  .map(node => node.href = node.href + 'John=Doe');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download