Home > Back-end >  Document.querySelector() is not showing all elements
Document.querySelector() is not showing all elements

Time:12-03

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.

enter image description here

Result of Relative JSPath.

enter image description here

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 an Array, it is possible to iterate over it with forEach(). It can also be converted to a real Array using Array.from(). However, some older browsers have not implemented NodeList.forEach() nor Array.from(). This can be circumvented by using Array.prototype.forEach().

Syntax:

elementList = parentNode.querySelectorAll(selectors);

Using CssSelector

While using a or a 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();
  • Related