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

Leave a Reply

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