Reputation: 630
A page has lots of links in it and I need to quickly click the links with text "Delete" in it. This causes AJAX request so a little pause is needed. What would be the javascript bookmarklet code (with no libraries, e.g. jQuery) which will quickly call the onclick() event binded to the links directly as an attribute but only those with text "Delete"?
As far as I can do it myself I get:
javascript:
(function(){
var links = document.getElementsByTag('a');
for(var i = 0; i <= links.length; i++){
if(links[i].innerHTML == "Delete"){
setTimeout("links[i].onclick()", 500); // pause for previous AJAX to proceed
}
}
})();
Upvotes: 0
Views: 1705
Reputation: 6268
Try this:
javascript:j=0;l=document.links;for(var i=0;i<l.length;i++){if(l[i].innerHTML.toLowerCase().indexOf("delete")!=-1){setTimeout("l["+i+"].onclick();",j*500+1);j++;}}
Notice several things. First, I just checked if the HTML inside the link tag contained the word delete. If there was any additional HTML or text inside the link tag, your code wouldn't work. Second, the command in setTimeout fixes a scope problem, wherein the variable i wouldn't exist when setTimeout was run. Finally, notice that the timeout is specified as j*500, with j being a separate variable incremented every time a "delete" link is found. setTimeout does not wait the half second, run the code, and return. Rather it returns immediately, then runs the code later, when specified. Doing it this way, the first link would be clicked in one millisecond (0*500+1=1), the second one in 501 milliseconds, the next in 1001, etc.
I also want to mention that the latest version of Firefox doesn't seem to support typing bookmarklets directly in the address bar. You have to use the Web Console (Ctrl+Shift+K) or JavaScript scratchpad (Shift+F4) to run snippets like this. If you do it that way, remove the javascript: part at the beginning.
Upvotes: 2
Reputation: 2190
onclick
often can't be used like that - sometimes the event is not directly bound to the object. This solution simulates the click. Instead you must use element.eventDispatch
, I found it by search for how to trigger events.
So here is something that's supposed to work:
(function(){
// First we create the event
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var links = document.getElementsByTag('a');
for(var i = 0; i <= links.length; i++){
if(links[i].innerHTML == "Delete"){
// And here, we trigger the event
setTimeout("links[i].dispatchEvent(evt)", 500); // pause for previous AJAX to proceed
}
}
})();
I'm not sure of your method to wait for the AJAX requests. The "correct" way would be to work out when the request, but for your task a second or a half might be enough.
Upvotes: 2