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.


Example:


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:
http://www.w3schools.com/js/js_htmldom_elements.asp



Content posted is based on learning or working experience, please leave comments if anything needs to be added or updated, discuss your queries on our facebook:qavalidation.com, Thanks!

Leave a Reply

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

%d bloggers like this: