Issue
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?
Solution
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
Answered By - Rajdeep Debnath
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.