Make Selenium Easy

Part 6: Usages Of Javascripts In Selenium: Locating WebElements Using JavaScript Commands

Hello Folks,

In this post, We will learn about javascript commands which we can use to locate a web element on web page.

When to use javascript commands to locate web element?

We already have enough locators in Selenium webdriver, which help us in identifying web elements on a web page. But sometimes, these locating strategies fail when web element is hidden or it is deeply nested. When we perform any action on these types of web elements, it doesn’t work. If an y website has a lot of AJAX calls, in that case also javascript locating commands are very useful.

Javascript commands to locate web elements:

Javascript provides below command to locate web elements on a web page which are given below:

  1. getElementById
  2. getElementsByClassName
  3. getElementsByName
  4. getElementsByTagName

If you notice, first command has “element” and remaining three have “elements”. Since, id is unique, so it will always return single element which other attributes like Class Name, Name and Tag Name are not unique, so they might return more than one elements.

We will see an example for command “getElementById” :

Output:

Now, we will see an example for command “getElementsByClassName” :

Output:

Hope, you will have proper understanding of above javascript commands to locate web element son web page. When you are not able to locate or perform action on web element then try JavaScript way once.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

Table of Contents

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.