Automated clicking on HTML elements

On a HTML page, elements can be retrieved either by using the getElementsByClassName or the getElementById method.

The getElementById method returns just one element, while the getElementsByClassName method returns an array of elements. On  a web site that I frequently visit, I often had to click an HTML element to get the updated status, since it refreshes very often. It automatically refreshes every 5 seconds, but if you click it, it can refresh instantly, instead of at the fifth-second interval. Since I'm a lazy person, I decided to automate the process, as all browsers have a Javascript console.

Here's what the HTML element looks like:

I decided to find out the ID of the HTML element.

<a href="#" class="refresh-widget" title="Refresh">

Unfortunately, it has no ID. It doesn't matter. Since it has a class,  I decided to try retrieving it by class name from the browser's Javascript console. So I entered documents.getElementsByClassName into the console:

It appears there's only 1 element by that name. So I came up with the following code:



I retrieved the elements, selected the first element, and called the click method. Since there's another HTML element by the class of "Button Success" that I wanted to click on, the above code became:

var clickRefreshWidget = true;
function clickRefresh() {
  ImStillHere = document.getElementsByClassName("Button Success");
  if (ImStillHere.length > 0) 
  if (clickRefreshWidget)
setInterval(clickRefresh, 1000);

As the "Button Success" element doesn't always appear, I checked the length of the array to ensure it's valid before clicking on the first element. Then, to invoke the code every 1 second, I passed the name of the function to setInterval, which calls a function at every specified interval. And anytime I wanted to stop the script, I just toggle the value of the clickRefreshWidget variable.

Published Fri, 15 Dec 2017 @ 9:36 AM by chuacw
Related articles: