0

While creating Selenium automation tests sometimes we need to retrieve a web element with JavaScript, not with Selenium driver.findElement.
So, I know we can do something like

javaScript = "document.getElementsByClassName('myClassName')[0].click();"
driver.execute_script(javaScript)

I see we can locate elements in this way ByClassName, ByName, ByTagName and BytagNameNS but in most cases element can be uniquely located with CSS Selector or XPath only while I couldn't see such way in documentations and tutorials.
So, I'm wondering is it possible to locate web elements with JavaScript by XPath or CSS Selectors?

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • CSS selectors can be used via [querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) or [querySelectorAll](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll). For XPath you can use [evaluate](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate) – Reyno Jun 03 '21 at 10:38
  • 1
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) -> [Locating DOM elements using selectors - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors), [Is there a way to get element by XPath using JavaScript in Selenium WebDriver?](https://stackoverflow.com/questions/10596417) – Andreas Jun 03 '21 at 10:40
  • For Xpath with JavaScript see: https://developer.mozilla.org/en-US/docs/Web/XPath/Introduction_to_using_XPath_in_JavaScript – Siebe Jongebloed Jun 03 '21 at 10:40

1 Answers1

1
document.querySelector() //for single node with css like path or selector

document.querySelectorAll() //for multiple nodes

To select by ID:

document.querySelector('#ID') //returns single element
document.querySelectorAll('#ID') //returns node list, you may need to use forEach

To select by class:

document.querySelector('.class') //returns single element
document.querySelectorAll('.class') //returns node list, you may need to use forEach

To select inside div by class:

document.querySelector('div > .class') //returns single element
document.querySelectorAll('div > .class') //returns node list, you may need to use forEach

Here is the documentation

Vivek Bani
  • 3,703
  • 1
  • 9
  • 18
  • _"To select by ...:"_ is not code, hence it shouldn't be formatted as such. And there are definitely similar questions here on SO. – Andreas Jun 03 '21 at 10:43