Joackim Karlsson Joackim Karlsson - 2 months ago 6
Javascript Question

JavaScript click href without ID

I'm on a site where I would like to grab all the href links and click it. I know I could do this.

document.getElementById('yourLinkID').click();
how ever, the issue is the href dosen't have an id, only a title. Can I somehow click all the href by it's title?

Answer

You can use document.querySelectorAll() with selector a[href] to retrieve all <a> elements having href attribute set, or [href] to retrieve all elements having an href attribute set; for..of loop to iterate collection

var hrefs = document.querySelectorAll("a[href]");
for (let elem of hrefs) {
  // do stuff
  console.log(elem.href);
}
Comments