Prophet
Prophet

Reputation: 33361

Locate web elements with JavaScript by CSS Selector or XPath?

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?

Upvotes: 0

Views: 1991

Answers (1)

Rajdeep D
Rajdeep D

Reputation: 3910

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

Upvotes: 1

Related Questions