Execute javaScript (locators) in selenium to identify HTML element

We have seen how to identify web elements using selenium locators…there are situations where selenium alone can’t able to identify web elements, there we can execute javaScript commands in selenium…

JavaScript has it’s own locators to identify web elements:

getElementById – Returns single element that matches the ID.

getElementsByName – Returns list of web elements with name same as provided name.

getElementsByClassName – Returns list of elements with provided classname.

getElementsByTagName – Returns list of elements with provided tagname.

we can even use xpath and CSSSelector to identify HTML elements:
For CSSSelector, we use document.querySelector or document.querySelectorAll

document.querySelector returns 1st element in DOM that matches the CSSSelector provided.


Note: use escape double quotes (” instead “) inside the querySelector argument to avoid error in execution.

document.querySelectorAll returns list of all html elements in DOM that matches the CSSSelector provided.
Note: Store the returned elements in a List and then do actions one by one either by for loop or iterator and perform actions on elements.

For more information on locating HTML elements, Refer:

Content posted is based on learning or working experience,
Share the post with others if find useful,
Any queries?, leave comments or discuss on our facebook:qavalidation.com, Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *