0

Last year I asked a question similar to the question I am asking here-

Create a Bookmarklet that clicks multiple buttons on one page

The accepted answer works perfectly on a page that uses jQuery. However I need to get something similar working on a page that doesn't load jQuery. I tried to insert jQuery into the page in the bookmarklet but it refuses to load (the website doesn't allow it).

How do I convert the following to pure Javascript so that I can click multiple buttons on the page?

(function(){
    var UserFollowButton = $('button.UserFollowButton');
    var index = UserFollowButton.length-1;
    follow();

    function follow(){
        if(index >= 0){
            $(UserFollowButton[index--]).click();
            setTimeout(follow, 500);
        }
    }
})();
Community
  • 1
  • 1
iagdotme
  • 1,033
  • 2
  • 21
  • 38

1 Answers1

0

To get a list of UserFollowButton equivalent to the query you just ran, you should use getElementsByClassName("UserFollowButton") which gives you an HTMLCollection of elements with a particular class name. Then, you can filter that collection to elements with the tagName equal to BUTTON.

Then, to click it, simply apply the method DOMElement.click to each element in the array. You can do that using forEach.

Array.prototype.slice.call( // convert HTMLCollection to Array
    document.getElementsByClassName("UserFollowButton")
 ).filter(function(element) {
     return element.tagName === "BUTTON";
}).forEach(function(element){
    element.click();
});

If you want the timeout, then you can simply set UserFollowButton to Array.prototype.slice.call(document.getElementsByClassName("UserFollowButton")).filter(function(element) { return element.tagName === "BUTTON"; });, then do what you are currently doing, using UserFollowButton[i].click() instead of implicit jQuery conversions.

Instead of having a global variable you are indexing from, though, try keeping the array local, passing it as an argument, using pop to take the first element, and keep passing it to subsequent callbacks.

EyasSH
  • 3,679
  • 22
  • 36