简体   繁体   中英

Unable to access the href attribute of links

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

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}`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM