0

I want to access the href attribute of some links and make changes to them if they contain certain string. Here is my current code:

var all_links = document.querySelectorAll('a');
for(var i = 0; i <= all_links.length; i++) {
   if(all_links[i].href.includes('test')) {
     all_links[i].href = 'something.com/?' + all_links[i].href;
   }
}

The code keeps giving me error:

jquery.min.js:2 Uncaught TypeError: Cannot read property 'href' of undefined

However, there are definitely lot of links on the webpage. I could get all links in the console by using:

console.log(all_links[i]);

Why can't I access the href attribute?

Here is the question I was following: Get local href value from anchor (a) tag

Real Noob
  • 1,369
  • 2
  • 15
  • 29
  • 1
    change `i <= all_links.length` to `i < all_links.length`. Otherwise it will always try to read one more element than there are elements in the list. The error only occures when your code tries to do this: `undefined.href` – wuerfelfreak Aug 11 '19 at 19:32

1 Answers1

0

You need to replace <= with < since arrays are zero indexed.

for(var i = 0; i < all_links.length; i++)

Or use filter and forEach

Array.from(document.querySelectorAll('a'))
    .filter(({href}) => href.includes('test'))
    .forEach(link => link.href = `something.com/?${href}`);
baao
  • 71,625
  • 17
  • 143
  • 203