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?

3

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

"To select by ...:" is not code, hence it shouldn't be formatted as such. And there are definitely similar questions here on SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.