为所有<a> objects that begin with a specific ID

时间:2016-11-03 15:12:56

标签: javascript

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 <a> 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.

2 个答案:

答案 0 :(得分:0)

// first, get list of all 'a' tags and convert to array
[].slice.call(document.querySelectorAll('a'))

  // 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
  .forEach(node => node.href = node.href + '?John=Doe');

答案 1 :(得分:0)

尝试获取以&#34; actionMenu&#34;

开头的所有链接数组
var linkArray = document.querySelectorAll('a[id^=actionMenu]')

然后遍历数组:

for(var i=0; i<linkArray.length; i++) {     
     var newHref = linkArray[i].href + "?John=Doe"; //your new href
     linkArray[i].href = newHref ; //change href
}

我希望这会有所帮助