How To Find Elements In A Webpage Using JavaScript

This article will discuss finding an element using Javascript.

In my last article, I have explained about JavascriptExecutor and covered the below points.

As I have mentioned in my above article, JavascriptExecutor is used for performing Javascript operations in a web browser from Selenium web driver.

The javascript operations can be performed on two things.

  1. Web Elements
  2. Web Page

So to perform any operations on web elements, first of all, we need to find the elements in the browser.

We all know how to find the elements using the Selenium web driver, if you don't know please follow the below article.

Overview Of Selenium Locators

Now we will learn "how to find the elements using javascript".

Just like in the Selenium web driver, JavaScript also provides some methods to find the elements.

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

Here if you observe carefully, we have only one single method(getElementById) which returns the webelement and the rest return the list of webelements.

All these methods are available in the document.

In the Selenium web driver, we try to find the element on the driver instance because the driver instance is holding the browser instance but in javascript, we are finding the elements on the document because here we are querying the DOM (Document object model).

Here I'm using below HTML code below to demonstrate these Javascript element-finding methods.

<div class='container'>    
    <input type='text' id='username' />    
    <input type='text' name='password' />    
    <input type='text' class='loginForm' />    
    <button>Signin</button>    
    <a href='#'>Signup</a>    
</div>

getElementById

This method queries the document to get the element based on its id attribute value.

Syntax

document.getElementById(<<id>>);

Parameters

  • id: The id attribute value of an element.
  • Return value: if the element is found then it returns the element, if the element is not found then it returns null.

In the above HTML code snippet, we have an ID attribute for the first textbox so we use that id value to get the element.

Usage in Selenium code

String javascript = "document.getElementById('username')";
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebElement element = (WebElement) jsExecutor.executeScript(javascript);

Generally, this is the only method that returns a single element because in a web application, the id attribute values are the most unique values.

getElementsByName

This method queries the document to get the element(s) based on their name attribute value.

Syntax

document.getElementsByName(<<name>>);

Parameters

  • name: The name attribute value of an element(s).
  • Return value: If the element(s) are found then it returns the NodeList (Collection) of element(s), if the element(s) are not found then it returns an empty NodeList.

In the above HTML code snippet, we have a name attribute for the second textbox so we use that name attribute value to get the element.

Using this method if you want to get only one element just like in selenium web driver(driver.findElement(By. Name(<<name>>))), you can use the index.

document.getElementsByName(<<name>>)[0];

Usage in Selenium code

String javascript = "document.getElementsByName('password')[0]";
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebElement element = (WebElement) jsExecutor.executeScript(javascript);

getElementsByClassName

This method queries the document to get the element(s) based on their class attribute value.

Syntax

document.getElementsByClassName(<<className>>);

Parameters

  • className: The className attribute value of an element(s).
  • Return value: if the element(s) is found then it returns the NodeList (Collection) of element(s), if the element(s) is not found then it returns an empty NodeList.

In the above HTML code snippet, we have a class attribute for the third textbox so we use that class attribute value to get the element.

Using this method if you want to get only one element just like in selenium webdriver(driver.findElement(By.ClassName(<<className>>))), you can use the index.

document.getElementsByClassName(<<className>>)[0];

Usage in Selenium code

String javascript = "document.getElementsByClassName('loginForm')[0]";
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebElement element = (WebElement) jsExecutor.executeScript(javascript);

getElementsByTagName

This method queries the document to get the element(s) based on their tag name.

Syntax

document.getElementsByTagName(<<tagName>>);

Parameters

  • tagName: The tagName of an element(s).
  • Return value: if the element(s) is found then it returns the NodeList (Collection) of element(s), if the element(s) is not found then it returns an empty NodeList.

In the above HTML code snippet, we have a button element whose stage name is button. So we use that tagName to get the element.

Using this method if you want to get only one element just like in selenium webdriver(driver.findElement(By.TagName(<<tagName>>))), you can use the index.

document.getElementsByTagName(<<tagName>>)[0];

Usage in Selenium code

String javascript = "document.getElementsByTagName('button')[0]";  
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;  
WebElement element = (WebElement) jsExecutor.executeScript(javascript);

Here you might be thinking something like, what if my target element is not have any of these attributes, in that case, how can I find the element(s)?

In the selenium web driver, we have other ways to find the element(s) like XPath and CSS selector.

If you want to find the element in javascript also using XPath and CSS selector, we have a way to do that.

But we are not able to find those methods along with the above-mentioned methods right?

That is because those methods' names are quite different here in JavaScript, those are.

  1. querySelector
  2. evaluate

querySelector

This method is used for finding an element using a CSS selector.

Syntax

document.querySelector(<<cssSelector>>);

Parameters

  • cssSelector: The cssSelector expression to find the target element.
  • Return value: if the element is found then it returns the element, if the element is not found then it returns null.

In the above HTML code snippet, we have a link that doesn't have any attribute values like id, name, and className. so we use that tag name to write the CSS selector.

Usage in Selenium code

String javascript = "document.querySelector('a')";
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebElement element = (WebElement) jsExecutor.executeScript(javascript);

evaluate

This method is used for finding an element using XPath.

Syntax

document.evaluate(
    xpathExpression,
    contextNode,
    namespaceResolver,
    resultType,
    result
).singleNodeValue;

Parameters

  • XPath expression: The XPath expression to find the target element.
  • contextNode: From which context do you want to start the search?
  • namespaceResolver: This is used when handling XML documents, so for HTML we can give null.
  • resultType: It is an integer that corresponds to the type of result XPathResult to return.
  • result: If you have already defined a variable for storing XPathResult, we can use that here or you can pass null (It will create a new XPathResult)
  • Return value: If the element is found then it returns the element, if the element is not found then it returns null.

In the above HTML code snippet, we have a link that doesn't have any attribute values like id, name, and className. So we use that link's text to write the XPath.

Usage in Selenium code

String javascript = "document.evaluate('//a[text()=\"Signup\"]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;";
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebElement element = (WebElement) jsExecutor.executeScript(javascript);

Here in every code, I have written the below line.

WebElement element = (WebElement) jsExecutor.executeScript(javascript);

By default, the executeScript method will return an object because in HTML DOM every element is treated as an object only.

To store that object instance into WebElement, I have typecast the object into WebElement.

So this is how we have to find the elements in a webpage using JavaScript.

In my next articles, we will see how we can perform click operation and enter text into a textbox, etc...

I hope you find this article useful. Please provide your valuable feedback, questions, or comments about this article.


Similar Articles