What is a Selenium WebElement?
A WebElement in Selenium represents an HTML element on a web page, allowing interaction (click, send keys, retrieve text) through methods like click(), sendKeys(), and getText(). WebElements provide methods to interact with those elements, retrieve information, and verify element properties.
When you use Selenium to automate a web browser, you’ll need to identify elements on the page and interact with them. Selenium WebElement objects are how you manage those interactions. These elements are found using different locators
The WebElement interface in Selenium enables interaction with both visible and hidden elements on a web page. WebElement command returns either null/void or the element found.
Syntax of Selenium WebElement
<start tag> content </end tag>
- HTML elements can contain other elements. Every HTML document carries such HTML elements.
- WebElement Selenium WebDriver methods apply to almost all DOM elements on a web page.
- Each WebElement is represented in Selenium via the WebElement interface – which is used by Selenium to interact with visible and invisible elements on the web page.
Every Selenium WebDriver method either returns a value or returns null/void (no value). The WebElement class in Selenium WebDriver works the same way.
Here’s an example of a WebElement in Selenium command:
WebElement element = driver.findElement(By.id(“UserName“));
This command returns either the element being searched for or returns null/void.
All actions on any WebElement will always populate against any element, regardless of whether an action is valid on the element or not.
List of Selenium WebElement Commands
There are different types of WebElement Commands in Selenium to interact with the web elements. These methods use the Web elements to interact with both visible and hidden elements on a web page. Methods in Selenium either return a value or nothing (null/void).
Selenium WebElement Methods
- sendKeys() – Type text into input fields.
- isDisplayed() – Check if the element is visible on the page
- isSelected() – Check if the element is selected
- submit() – Submits a form or triggers a submit action on a form element
- isEnabled() – Check if the element is enabled
- getLocation() – Returns values of the x and y coordinates of the WebElement relative to the top-left corner of the viewport.
- clear() – Clear text from an input field
- getText() – Get the visible text inside the WebElement.
- getTagName() – Returns the tag name of the WebElement as a string. The tag name is the type of the HTML element.
- getCssValue() – Get the value of a specified CSS property of a WebElement.
- getAttribute() – Get the value of a specific attribute of the element
- click() – Click on the WebElement
- getSize() – Returns values of height and width of the WebElement.
Here is the detailed list of WebElements Commands in Selenium:
1. sendKeys() command
sendKeys command allows the user to type content automatically into an editable field while executing tests. These fields are web elements that can be identified using locators like element id, name, class name, etc.
Syntax:
element.sendKeys(“text”);
This method uses CharSequence as a parameter. It returns nothing. It works with text entry elements such as INPUT and TEXTAREA.
Example:
// Create WebElement WebElement elesendKeys = driver.findElement(By.id("TextBox")); // Perform sendKeys operation elesendKeys.sendKeys("Cheese"); // OR // Send value to particular WebElement e.g: Textbox. driver.findElement(By.id("TextBox")).sendKeys("Cheese");
Read More: Quick XPath Locators Cheat Sheet
2. isDisplayed() command
The isDisplayed command in Selenium verifies if a particular element is present and displayed. If the element is displayed, then the value returned is true. If not, then the value returned is a NoSuchElementFound exception.
Syntax:
element.isDisplayed();
The code below verifies if an element with the id attribute value next is displayed.
boolean eleSelected= driver.findElement(By.xpath("xpath")).isDisplayed();
Example:
WebElement element = driver.findElement(By.id("UserName")); boolean status = element.isDisplayed(); //Or can be written as boolean status = driver.findElement(By.id("UserName")).isDisplayed();
Note: If an element is present on a web page but its property is set to hidden, the Selenium WebDriver isDisplayed method will return NoSuchElementFound. This is because even though the element is present in the DOM, it is not visible to users.
3. isSelected() command
This command only works on input elements such as radio buttons, checkboxes, select options, and menu items. It is used to determine if an element is selected. If the specified element is selected, the value returned is true. If not, the value returned is false.
Syntax:
element.isSelected();
Example:
WebElement element = driver.findElement(By.id("Sex-Male")); boolean status = element.isSelected(); //Or can be written as boolean staus = driver.findElement(By.id("Sex-Male")).isSelected();
4. submit() command
This command is handy when interacting with forms (or elements within a form) on a web page. It doesn’t require a parameter and returns nothing.
As evident from its name, the command submits relevant information (as required) on a website. If the action triggered by this command changes the current web page, the method will wait until the new page loads.
Syntax:
element.submit();
Example:
WebElement element = driver.findElement(By.id("SubmitButton")); element.submit(); //Or can be written as driver.findElement(By.id("SubmitButton")).submit(); WebElement element = driver.findElement(By.id("SubmitButton")); element.submit(); //Or can be written as driver.findElement(By.id("SubmitButton")).submit();
5. isEnabled() command
This WebElement in Selenium command verifies if an element is enabled on the web page. If the element is enabled, it returns a true value. If not, it returns a false value.
Syntax:
element.isEnabled();
The code below verifies if an element with the id attribute value next is enabled.
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();
Example:
// Create WebElement WebElement eleEnabled = driver.findElement(By.id("TextBox")); // Perform isEnabled operation eleEnabled.isEnabled(); // OR // Verify WebElement is Enabled or Not? e.g: Radio / Checkbox. driver.findElement(By.id("Text")).isEnabled();
6. getLocation() command
This command retrieves the location of a specified element on a web page. It does not require a parameter and returns the Point object as its result. The X and Y coordinates of the element can be derived from the Point object returned.
Syntax:
element.getLocation();
Example:
WebElement element = driver.findElement(By.id("SubmitButton")); Point point = element.getLocation(); System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y);
7. clear( ) command
When using this WebElement in Selenium command, its value will be cleared if the element in question is a text entry. It doesn’t require a parameter and returns nothing.
Syntax:
element.clear();
The clear() method does not affect other web elements. The text entry elements here are INPUT and TEXTAREA.
Example:
// Create WebElement WebElement eleClear = driver.findElement(By.id("TextBox")); // Perform clear operation eleClear.clear(); // OR // Clear particular WebElement e.g: Textbox. driver.findElement(By.id("TextBox")).clear();
8. getText() command
This command retrieves the text within a specific web element. This includes the inner text as well as the sub-elements sans whitespace. It doesn’t require a parameter and returns a string value. This method is often used to verify labels, messages, error, and other elements (involving text) displayed to website visitors.
Syntax:
element.getText();
Example:
// Create WebElement WebElement elegetText = driver.findElement(By.id("TextBox")); // Perform getText operation elegetText.getText(); // OR // Get text of Particular WebElement & Store into String driver.findElement(By.id("TextBox")).getText();
9. getTagName() command
This method retrieves the tag name of the specified element. It does not require a parameter and returns a string value as its result.
Syntax:
element.getTagName();
This command does not return the value of the name attribute. It returns the tag. For example, if the code is <input name=”foo”/>, then this command will return the tag, i.e. “input”.
Example:
// Create WebElement WebElement elegetTagName = driver.findElement(By.id("TextBox")); // Perform getTagName operation elegetTagName.getTagName(); // OR // Able to get TagName of Particular WebElement & Store into String driver.findElement(By.id("TextBox")).getTagName(); // Create WebElement WebElement elegetTagName = driver.findElement(By.id("TextBox")); // Perform getTagName operation elegetTagName.getTagName(); // OR // Able to get TagName of Particular WebElement & Store into String driver.findElement(By.id("TextBox")).getTagName();
10. getCssValue() command
This command retrieves the CSS property value of a specified element. It does not require a parameter and returns a string value as its result.
Syntax:
element.getCssValue();
- Color values must be returned as rgba strings. For example, if the “background-color” property is set as “green” in the HTML source, the value returned by the command will be “rgba(0, 255, 0, 1)”.
- Shorthand CSS properties (e.g. font, background, border, margin, border-top, margin-top, padding, padding-top, outline, list-style, pause, cue) are not returned, as required with DOM CSS2 specifications. Access the longhand properties directly in order to access the desired values.
Example:
//Locating textBox element using CSS Selector WebElement textBox = driver.findElement(By.cssSelector("div#textBox ")); //Performing sendKeys operation on the element textBox.sendKeys("stqatools");
11. getAttribute() command
This command retrieves the attribute value of a specified element. It uses String as the parameter and returns a string value as its result.
Syntax:
element.getAttribute();
Example:
WebElement element = driver.findElement(By.id("SubmitButton")); String attValue = element.getAttribute("id"); //This will return "SubmitButton"
12. click() command
The click() command lets the tester replicate the click action on a button, link, radio button or checkbox. In Webdriver, the click occurs after the element is found. In Selenium IDE, the recorder identifies the element, the command itself performs the click.
Syntax:
element.click();
Example:
// Create WebElement WebElement eleclick = driver.findElement(By.id("TextBox")); // Perform click operation eleclick.click(); // OR // Click on any WebElement e.g: Button. driver.findElement(By.id("Button_Id")).click(); // Create WebElement WebElement eleclick = driver.findElement(By.id("TextBox")); // Perform click operation eleclick.click(); // OR // Click on any WebElement e.g: Button. driver.findElement(By.id("Button_Id")).click();
13. getSize() command
This command retrieves the height and width of a specific rendered element. It does not require a parameter and returns the Dimension object as its result.
Syntax:
element.getSize();
Example:
WebElement element = driver.findElement(By.id("SubmitButton")); Dimension dimensions = element.getSize(); System.out.println(“Height :” + dimensions.height + ”Width : "+ dimensions.width);
Why use BrowserStack Automate to run Selenium Tests?
You should run Selenium Tests on a real device cloud like BrowserStack Automate for below reasons:
- Realistic Testing Conditions: Real device clouds provide access to a broad spectrum of devices and environments, ensuring tests reflect actual user conditions accurately.
- Enhanced Security: Maintained with high security standards, real device clouds offer secure, isolated testing environments, minimizing data breach risks.
- Broad Browser and OS Coverage: Helps identify compatibility issues across various browsers and operating systems, enhancing user experience.
- Performance Insights: Real devices yield authentic performance data essential for optimizing application responsiveness.
- Scalability and Accessibility: Facilitates scalable and accessible testing, suitable for distributed teams.
- CI/CD Integration: Integrates smoothly with CI/CD pipelines for continuous testing and early issue detection.
- Cost-Effectiveness: Although initially more costly, it saves on long-term expenses related to fixes and support.
Conclusion
WebElement in Selenium commands are essential for testers seeking to automate user actions on a website to verify its performance. The commands mentioned above will go a long way in the thorough automation testing of websites. Selenium tests yield the best result when run on a real device cloud.