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?
-
could you add your code here?Nitin Kumar– Nitin Kumar2016-09-24 06:36:24 +00:00Commented Sep 24, 2016 at 6:36
-
1Possible duplicate of Getting element by a custom attribute using JavaScriptDaniel Gasser– Daniel Gasser2016-09-24 06:38:11 +00:00Commented Sep 24, 2016 at 6:38
5 Answers
Accessing the document.links array would be the solution you are looking for.
From there, though, clicking one would cause the page to navigate away to its target, and the script would stop executing. If you must click them all, what you could do is loop through them, and set the target of an iframe with the link's href attribute.
Comments
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);
}
1 Comment
var hrefs = document.querySelectorAll('[title=title_name"]'); How ever, it will only click the first thing than break. But that should not be hard to solve. Cheers!use querySelectorAll:
document.querySelectorAll("[title=foo]")
Which will give you an array. iterate through the array if your goal is to click all the links. obviously, clicking a link will redirect you to that page and will pause script execution.
a dirty solution would be to use:
selectedElement.setAttribute('target', '_blank');
where selectedElement is the link's selector. this makes the url open in a new tab.
Comments
No idea why you would want to do this as each <a href... will be activated and after the first one it will be up to the browser to work out what happens.
var aList = document.getElementsByTagName('a');
var i, max = aList.length;
for(i=0;i<max;i++) {
aList[i].click();
}
<a href="#" onclick="console.log('a1');return false">Hello</a>
<a href="#" onclick="console.log('a2');return false">world</a>