I am trying to create a script that clicks a button every 31 seconds.
That website contains many buttons with the classes reply-markup-button rp tgico
. To select the exact button I am looking for, I am looking for the exact text on the button using document.getElementByTagName
and a for-loop:
var viewAdsButton = document.getElementsByTagName("button");
var viewAdsButtonText = "View ads";
setInterval(function() {
for (var i = 0; i < viewAdsButton.length; i++) {
if (viewAdsButton[i].textContent == viewAdsButtonText) {
viewAdsButton[i].click()
}
}
}, 31000);
<button class='reply-markup-button rp tgico' onclick="console.log('button 1')">View ads</button>
<button class='reply-markup-button rp tgico' onclick="console.log('button 2')">View ads</button>
<button class='reply-markup-button rp tgico' onclick="console.log('button 3')">Don't View ads</button>
<button class='reply-markup-button rp tgico' onclick="console.log('button 4')">View ads</button>
The issue is that there are also many buttons with "View ads" on them, and I only want the script to click the first one instead of all of them.
3
Answers
Add a call to
break
(orreturn
) after you click the first matching button:If there are many buttons, don’t try to use
document.getElementsByTagName
ordocument.getElementsByClassName
. They return a collection of elements and it’s much harder to find the exact element you want. Also consider this: what if two buttons have the same text, or the website updates and the button text changes?Here are some better approaches:
First, look at the button in your browser’s dev tools. If it has an ID, then use
document.getElementsById
. Like this:If the button doesn’t have an ID, then you should get the element by its XPath. An XPath is just a string that uniquely represents an element in the DOM hierarchy, but this isn’t too important. You can copy the elements XPath in the dev tools (Copy -> Copy XPath). Use this code for the XPath:
(See this answer for more on getting an element by its XPath)
Instead of using
getElementsByTagName()
, I grabbed the first button with the classes you listed usingquerySelector()
. Then you can just add a click event inside thesetInterval()
function without looping through anything.I also used
querySelectorAll()
and did aforEach()
loop to add an onclick event listener to every button with those classes, to show that thesetInterval()
function was only clicking the first one.