JavaScript to click element with class but no ID

What if my element (Search button) has only a class and no id ? How to deal with this ?

@youssef.boudhaouia I wasn’t happy resurrecting an old thread to answer this so I split to a new topic.

To answer your question directly…

document.querySelector(".my-class").click()

However, there could be issues with that call. Unlike IDs, classes don’t have to be unique and frequently are not, so the selector ".my-class" might resolve to more than one element on the page. There are many ways to solve that, but to choose the best one, I need to see more of your HTML - take a screenshot in DevTools and show me the HTML code.

@youssef.boudhaouia You can also use an id of another element that is nearby using xpath attributes, like:
id("businessCore")/../preceding-sibling::div/div[2]/button[@class="my-class"]

There are many instances of this on this forum as well as other sites.
https://www.w3schools.com/xml/xpath_syntax.asp

1 Like