Reputation: 653
Am looking for how to click links on my page using javascript. In my page i show each record from my database . and a 'show' link to the right clicking it will expand and display the row in detail. i want to expand all the rows at once . Is it possible to click link in Javascript like this?
Upvotes: 2
Views: 6912
Reputation: 375
The following snippet does not require jQuery:
<script>
const dumpToggleLinks = document.getElementsByClassName('sf-dump-toggle');
for (let i = 1; i < dumpToggleLinks.length; i++) {
dumpToggleLinks[i].click();
}
</script>
Upvotes: 0
Reputation: 268344
You can cycle through all of the anchors, and click them, yes:
var myLinks = document.getElementsByTagName("a");
for (var i = 0; i < myLinks.length; i++) {
myLinks[i].click();
}
Note that this will click every link on the page. You can focus more on a specific set of links by going through a parent container that sits just outside of them:
var myLinks = document.getElementById("container").getElementsByTagName("a");
This would get all links within the element having the id
value of "container".
Update2:
Within the comments, you wanted to know how to click only links whose ID
begins with a specific string. Let's look at a couple ways we can implement that into our aforementioned code:
Using jQuery, you could click all id='reviews-show...'
links like this:
$("a[id^='reviews-show']").click(); // simple, eh?
The ^=
in this selector matches in a regular-expression style, asking if the string starts with "reviews-show," which will retrieve only the a
tags for which this statement is true.
If you want to stick with just regular javascript, we can modifiy our first code-block to check the substring:
var myLinks = document.getElementsByTagName("a");
for (var i = 0; i < myLinks.length; i++) {
currentlink = myLinks[i];
if (currentlink.id.substring(0,12) === "reviews-show") {
currentlink.click();
}
}
Update:
Apparently jQuery is rotting my mind, and my solution doesn't work as-is. If you don't mind using jQuery (you'd love it), you could go this route:
$("a").click(); //clicks all links on page
$("#container a").click();//clicks all links within element having id 'container'
If you want to stay away from a framework, try adding this prototype extension into the top of your code which will make my original answer sufficient:
HTMLElement.prototype.click = function() {
if (document.createEvent) {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
} else if (this.fireEvent) {
this.fireEvent("onclick");
}
}
Source: http://www.barattalo.it/2009/11/18/click-links-with-javascript/
Upvotes: 4