简体   繁体   中英

How to get all links from a website by className, split the website name, and store within an array

I'm trying to get all the links from Gmail and store them within an array. I'm trying to get all the emails to be stored as such -

function gmailGetAllLinks(){
  var classname = document.getElementsByClassName('AO');
  var array1 = [];
  for(i=0;i<classname.length;i++){
      var str = classname[i].getElementsByTagName('a')[0].href;
      var res = str.split("?"); 
      array1.push(res[0]);

  }
  window.alert(array1)
  warningPopup()
}

When I try to print the array out as phishingWebsites.append = array1; it shows as just null, where doing window.alert shows only the first link.

It's simpler to use querySelectorAll('.AO a') to target all those anchors.

Then you can turn that collection into an array and use Array#map() to get the results

 function gmailGetAllLinks(){ const links = Array.from(document.querySelectorAll('.AO a')).map(link => { const url = new URL(link.href); url.search = ''; return url.toString(); }) console.log(links) } gmailGetAllLinks()
 .AO{ padding: 1em; border:2px solid #ccc; margin: 1em} a{display: block; margin-bottom:1em}
 <div class="AO"> <a href="https://google.com?q=foo">Google</a> <a href="https://samsung.com?q=foo">Samsung</a> </div> <div class="AO"> <a href="https://facebook?q=foo">Facebook</a> <a href="https://wikipedia.com?q=foo">Wikipedia</a> </div>

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