I am a novice and trying to design both relative CSS selectors and JSPath to run my automation scripts.
While on the way, I could find the return statements are different between these two. Please check the below example. Could someone tell what changes I need to make in JSPath to keep the results same as relative CSS selectors.
Result of Relative CSS selector.
Result of Relative JSPath.
JS just returns first element while the css selectors returned multiple above. What changes do I need to make in JS to keep the results same.
CodePudding user response:
Document.querySelector()
The Document
method querySelector() returns the first WebElement within the document that matches the specified selector, or group of selectors. If no matches are found, null
is returned.
Note: The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes.
Syntax:
element = document.querySelector(selectors);
Document.querySelectorAll()
The Document
method querySelectorAll() returns a static NodeList representing a list of the document's elements that match the specified group of selectors.
Note: Although
NodeList
is not anArray
, it is possible to iterate over it withforEach()
. It can also be converted to a realArray
usingArray.from()
. However, some older browsers have not implementedNodeList.forEach()
norArray.from()
. This can be circumvented by usingArray.prototype.forEach()
.
Syntax:
elementList = parentNode.querySelectorAll(selectors);
Using CssSelector
While using a xpath or a css-selectors would return a list of the document's elements that match the specified group of selectors.
Conclusion
As discussed above, when you use querySelector()
only the first matching element is returned. If your usecase is to return all the matching element, you need to use querySelectorAll()
as:
document.querySelector("div[slot^='Learner']>div>div>span")
CodePudding user response:
You have to use
document.querySelectorAll();