I'm trying to figure out a way to automatically click a button on a web page with a specific class, but only if there exists another element on the page with a different, specific class.
The way I imagine this is: 1) I load the page 2) the script checks for a specific element (via class) 3) if the element/class exists, the other specified element is clicked.
In doing this I figured I would use the HTML DOM querySelector() method by using classes from the HTML page for the given elements.
So if the following class exists on the page:
<span class="dashboardIcon dashboardIconFeatured">
I would like to click the element with this class:
<a class="surveyClicked markClicked">
Here is the code I have so far:
document.querySelector(".dashboardIcon.dashboardIconFeatured");
document.querySelectorAll(".surveyClick.markClicked")[0].click();
Both lines of code work individually on their own in the console. What I'm having trouble doing is bringing it all together and making sure the second line of code runs ONLY IF the first condition is satisfied - that the class dashboardIcon dashboardIconFeatured exists. It seems like a potentially easy fix, but my lack of JavaScript experience and familiarity with the syntax is hitting me.
Any and all help would be deeply appreciated! Cheers.
Try like this
var isMobileVersion = document.getElementsByClassName('dashboardIcon dashboardIconFeatured');
if (isMobileVersion.length > 0) {
console.log("element exists");
document.getElementsByClassName("surveyClicked markClicked")[0].click();
}
function func(){
console.log("clicked");
}
<span class="dashboardIcon dashboardIconFeatured">
<a class="surveyClicked markClicked" onclick="func()">