How To Find Elements In A Webpage Using JavaScript

In this article, will discuss about 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 webdriver.
 
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 selenium web driver, if you don't know please follow the below article:👇
Now we will learn "how to find the elements using javascript".
 
Just like in 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 are returning the list of webelements.
 
All these methods are available on the document.
 
In selenium web driver, we try to find the element on 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 to demonstrate these Javascript element finding methods,
  1. <div class='container'>    
  2.     <input type='text' id='username' />    
  3.     <input type='text' name='password' />    
  4.     <input type='text' class='loginForm' />    
  5.     <button>Signin</button>    
  6.     <a href='#'>Signup</a>    
  7. </div>     

getElementById

 
This method queries the document to get the element based on its id attribute value.
 
Syntax
  1. 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
  1. String javascript = "document.getElementById('username')";  
  2. JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;  
  3. 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
  1. 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.
  1. document.getElementsByName(<<name>>)[0]  
Usage in Selenium code
  1. String javascript = "document.getElementsByName('password')[0]";  
  2. JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;  
  3. WebElement element = (WebElement) jsExecutor.executeScript(javascript); 

getElementsByClassName

 
This method queries the document to get the element(s) based on their class attribute value.
 
Syntax
  1. document.getElementsByClassName(<<className>>);  
Parameters
  • className - The className 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 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.
  1. document.getElementsByClassName(<<className>>)[0]  
Usage in Selenium code
  1. String javascript = "document.getElementsByClassName('loginForm')[0]";  
  2. JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;  
  3. WebElement element = (WebElement) jsExecutor.executeScript(javascript);

getElementsByTagName

 
This method queries the document to get the element(s) based on their tagname.
 
Syntax
  1. document.getElementsByTagName(<<tagName>>);  
Parameters
  • tagName - The tagName 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 button element whose tageName 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.
  1. document.getElementsByTagName(<<tagName>>)[0]  
Usage in Selenium code,
  1. String javascript = "document.getElementsByTagName('button')[0]";  
  2. JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;  
  3. WebElement element = (WebElement) jsExecutor.executeScript(javascript);
Here you might be thinking somehting like, what if my target element is not having any of these attributes, in that case, how can I find the element(s)?
 
In the selenium web driver, we have the 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
  1. 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 tagName to write the CSS selector.
 
Usage in Selenium code
  1. String javascript = "document.querySelector('a')";  
  2. JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;  
  3. WebElement element = (WebElement) jsExecutor.executeScript(javascript); 

evaluate

 
This method is used for finding an element using XPath.
 
Syntax
  1. document.evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result).singleNodeValue;  
Parameters
  • xpathExpression - The XPath expression to find the target element.
  • contextNode - From which context you want to start the search.
  • namespaceResolver - This is used when handing with 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
  1. String javascript = "document.evaluate('//a[text()='Signup']',document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;";  
  2. JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;  
  3. WebElement element = (WebElement) jsExecutor.executeScript(javascript); 
Here in every code, I have written the below line: 
  1. WebElement element = (WebElement) jsExecutor.executeScript(javascript);   
By default, the executeScript method will return 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.