Skip to main content

Element Actions

Type


//a By object is used to store the locator to your element
private By elementLocator = By.id("username_textbox");
//click on target element
driver.element().type(elementLocator, "query");

TypeAppend

this method used for typing without clearing the texbox first


//a By object is used to store the locator to your element
private By textBoxLocator = By.id("username_textbox");
// type to empty textbox
driver.element().type(textBoxLocator, "Shaft");
// continue typing without erasing what was typed in the same field
driver.element().typeAppend(textBoxLocator , " engine");

TypeSecure


//a By object is used to store the locator to your element
private By elementLocator = By.id("username_textbox");
//click on target element
driver.element().typeSecure(elementLocator, "query");

TypeFileLocationForUpload

//locator of browse button or choose file button  
By chooseFileButtonLocator = By.xpath("//form//input[@type='file']");
//typeFileLocationForUpload method takes element locator and file path
driver.element().typeFileLocationForUpload(chooseFileButtonLocator, "src/test/resources/testDataFiles/testUpload.txt");

Clear

Clears the text from a text field or text area.

//a By object is used to store the locator to your element
private By textBoxLocator = By.id("username_textbox");
//clear the text field
driver.element().clear(textBoxLocator);

Click on an Element

In order to interact with elements appearing on web page you'll first need to locate the element using one of WebDriver's locating strategies(By methods) like ID, Class Name, XPath, CSS Selectors, link Text, Partial link text, Name, or Tag name.


//a By object is used to store the locator to your element
private By elementLocator = By.id("sign_in_btn");
//click on target element
driver.element().click(elementLocator);

The method click will wait for your target element to be interactable and then attempts to click on it using Selenium WebDriver, if that didn't work it will attempt to click using JavaScript

Click And Hold

driver.element().clickAndHold(elementLocator);

Waits for the element to be clickable, and then clicks and holds it.

Click Using JavaScript

driver.element().clickUsingJavascript(elementLocator);

Clicks an element using JavaScript. This is useful when the standard click method doesn't work due to element positioning or visibility issues.

Double Click​


//store the locator to your element
By elementLocator = By.className("double_click_btn");
//Double click target element
driver.element().doubleClick(elementLocator);

Hover

import org.openqa.selenium.By;
//The locator to your element
By elementLocator = By.tagName("span");
//Hover over target element
driver.element().hover(elementLocator);

Hover and click

  • Hover over an element to show hover menue then click on one of the displayed options
By clickable = By.xpath("//a[contains(text(),'Video Games ') ] ");
By hoverItem = By.linkText("Popular Toys");

driver.element().hoverAndClick(hoverItem, clickable);
  • for multi-level hover menus You need to hover on the category, then hover on a subcategory, and so on until you finally click on the clickable item.
public class HoverAndClickDemo {
List<By> hoverLocators =new ArrayList<By>();
By clickable = By.linkText("Car");

@Test
public void demo() {
hoverLocators.add(By.linkText("Popular Toys"));
hoverLocators.add(By.xpath("//a[contains(text(),'Video Games ') ] "));

driver = new SHAFT.GUI.WebDriver();
driver.browser().navigateToURL("https://phppot.com/demo/multilevel-dropdown-menu-with-pure-css/");
driver.element().hoverAndClick(hoverLocators, clickable);
}
}

hoverAndClick

Scroll To Element

By elementLocator = By.xpath("//a[@href='https://twitter.com/saucelabs']");

driver.element().scrollToElement(elementLocator);

Capture Screenshot

By elementLocator = By.xpath("//a[@href='https://twitter.com/saucelabs']");

driver.element().captureScreenshot(elementLocator);

Drag and drop

  • Drag an element into a target element
By sourceElement = By.id("draggable");    // Locator to the element you want to drag
By targetElement = By.id("destination"); // Locator to the destination element

driver.element().dragAndDrop(sourceElement,targetElement);
  • Drag an element to a specified position
By sourceElement = By.id("draggable");    // Locator to the element you want to drag
int xPos= 500;
int yPos= 500;

driver.element().dragAndDrop(sourceElement,xPos,yPos);
  • Drag an element by a specific offset
By sourceElement = By.id("draggable");    // Locator to the element you want to drag
int xOffset = 100; // Horizontal offset
int yOffset = 50; // Vertical offset

driver.element().dragAndDropByOffset(sourceElement, xOffset, yOffset);

Get Tag name

String TagName = driver.element().getTagName(ElementLocator);

Retrieves tag name from the target element and returns it as a string value.

Get the value of an element attribute

//The locator to your element
By googleSearchBox = By.cssSelector(".gLFyf.gsfi");
//get the value of the 'name' attribute
String attributeValue = driver.element().getAttribute(googleSearchBox, "name");

Returns the value of the given attribute as a String,you will allso be able to see something like this report
in the automatically generated Allure report, for more on that see Reporting.

Get the value of a CSS property

String propertyValue = driver.element().getCSSProperty​(elementLocator, "width");

Get context handle\s

you need to get the context handle in order to be able to switch back to it

  • Return the handle for currently active context.
String currentContext = driver.element().getContext();
  • Return a list of unique handles for all the currently open contexts.
driver.element().getContextHandles();

Switching focus to a different context

driver.element().setContext(currentContext);

Get window handle\s

you need to get the window handle in order to be able to switch back to it

  • Return the handle for currently active window.
String currentWindow = driver.element().getWindowHandle();
  • Return a list of unique handles for all the currently open windows.
driver.element().getWindowHandles();

Switching focus to a different window

switch driver's focus to a different window using its name or handle

driver.element().switchToWindow();

Handling IFrames

In order to interact with elements within IFrames you neeed to first change driver's focus to the IFrame, once done you will need to switch back to the original content

  • Switching focus to an IFrame
By iFrameLocator = By.id("ifr_id");
driver.element().switchToIframe(iFrameLocator );
  • Get the current frame reference
String currentFrame = driver.element().getCurrentFrame();

Returns the current frame reference as a string.

  • switching back to default content
driver.element().switchToDefaultContent();

Insert text into a text field

  • clear text inside a text field (if any), and insert new text value
driver.element().type(textFieldLocator, "any text you would like to type");
  • Append to existing text
driver.element().typeAppend(textFieldLocator, "text added to the end");

Perform Clipboard action

copy,cut or paste text

driver.element().clipboardActions(textFieldLocator, "copy");

supports the following actions "copy", "paste", "cut", "select all", "unselect"

Sample Code Snippet


public class TypingDemo {
By textField = By.id("tinymce");
By textIFrame = By.id("mce_0_ifr");

@Test
void type() {
driver = new SHAFT.GUI.WebDriver();
driver.browser().navigateToURL("https://the-internet.herokuapp.com/tinymce");
// switch focus to IFrame containing the text field
driver.element().switchToIframe(textIFrame );
//append text to the end
driver.element().typeAppend(textField, "this is added text");
// copy the whole paragraph
driver.element().clipboardActions(textField,"select all");
driver.element().clipboardActions(textField, "copy");
//replace original text using type
driver.element().type(textField, "new text that overrides old content , ");
//paste previously copied paragraph
driver.element().clipboardActions(textField, "paste");

}
}

Get elements count

to find the number of elements matching a specific locator

int numOfElements = driver.element().getElementsCount(locatorToMultipleElements);

Sample Code Snippet


public class Demo {
private By searchBox = By.name("q");
private By results = By.cssSelector("h3.LC20lb");

@Test
public void method() {
driver = new SHAFT.GUI.WebDriver();
driver.browser().navigateToURL("https://www.google.com");
driver.element().type(searchBox, "SHAFT_ENGINE");
driver.element().keyPress(searchBox, "ENTER");
int num = driver.element().getElementsCount(results);
System.out.println(num);

}
}

Get selected option from a drop down

//Locator to the Drop Down element
By dropDown = By.id("dropdown");
//Retrieve selected text and store it in a string variable
String SelectedItem = driver.element().getAttribute(googleSearchBox, "name");

Retrieves the selected text from the target drop-down list element and returns it as a string value.

Select an option from a drop down list

//Locator to the Drop Down element
By dropDown = By.id("dropdown");
//Retrieve selected text and store it in a string variable
driver.element().select(dropDown, "Option 1");

Set Value Using JavaScript

Sets the value of an element using JavaScript. This is useful when the standard type method doesn't work or when you need to set a value without triggering events.

By inputField = By.id("username");
driver.element().setValueUsingJavaScript(inputField, "myUsername");

Submit Form Using JavaScript

Submits a form using JavaScript. This can be used to submit a form programmatically without clicking the submit button.

By formElement = By.id("loginForm");
driver.element().submitFormUsingJavaScript(formElement);

Sample Code Snippet



public class DropDownDemo {

private By dropDown = By.id("dropdown");

@Test
public void method() {
driver = new SHAFT.GUI.WebDriver();
driver.browser().navigateToURL("https://the-internet.herokuapp.com/dropdown");
driver.element().getSelectedText( dropDown);
driver.element().select(dropDown, "Option 1");
driver.element().getSelectedText(dropDown);

}

}
  • To verify the results you can use traditional String variables, check SHAFT results in the Allure report (as shown in the image below), or you can use other verification techniques. report_2

Get size of an element

String elementSize = driver.element().getSize(TargetElementLocator);

Retrieves element size from the target element and returns it as a string value.

  • An alternative to using getCSSProperty​ to get width and height values separately

Get elements text

Retrieves text from the target text field and returns it as a string value.

String text = driver.element().getText(textBox);

Get state of an element

  • Check if an element is clickable
//The locator to your element
By elementLocator = By.id("submit_btn");
//Check if element is clickable
boolean isClickable = driver.element().isElementClickable(elementLocator);

Returns a boolean indicating whether the element is clickable (visible and enabled).

Advanced Example:

public class DynamicControlsDemo {
By textField=By.xpath("//form[@id='input-example']/input");
By changeState=By.xpath("//form[@id='input-example']/button");

@Test
public void alternate() {
driver = new SHAFT.GUI.WebDriver();
driver.browser().navigateToURL("https://the-internet.herokuapp.com/dynamic_controls");
//--1-- check that initially the text box is not clickable
System.out.println(driver.element().isElementClickable(textField));
//--2-- press the button to enable the text box
driver.element().click(changeState);
//--3-- check again whether the text box is clickable
System.out.println(driver.element().isElementClickable(textField));
//--4-- attempt to click on the text box
driver.element().click(textField);
//--5-- finally verify the state of the check box
System.out.println(driver.element().isElementClickable(textField));
driver.element().type( textField, "SHAFT is awesome !");
}
}

clickable

The text field is disabled by default,directly after clicking the enable button the isElementClickable method still returns false because the switching takes some time, the click method waits for target element to be clickable and places the cursor inside the text field, by then the text field is naturally clickable as shown in the previous image captured from the Allure report.

  • Check if an element is displayed
System.out.println(driver.element().isElementDisplayed(elementLocator));

returns a boolean indicating whether the element is displayed

Wait Methods

SHAFT provides several wait methods to handle synchronization and ensure elements are in the expected state before performing actions.

Wait Until Element Text Matches

Waits until the text of an element matches the expected value.

By elementLocator = By.id("status_message");
driver.element().waitUntilElementTextToBe(elementLocator, "Success");

Wait Until Attribute Contains Value

Waits until a specific attribute of an element contains the expected value.

By elementLocator = By.id("progress_bar");
driver.element().waitUntilAttributeContains(elementLocator, "class", "complete");

Wait Until Element is Selected

Waits until an element (like a checkbox or radio button) is selected.

By checkboxLocator = By.id("terms_checkbox");
driver.element().waitUntilElementToBeSelected(checkboxLocator);

Wait Until Number of Elements Equals

Waits until the number of elements matching a locator equals a specific count.

By listItemsLocator = By.className("list-item");
driver.element().waitUntilNumberOfElementsToBe(listItemsLocator, 5);

Wait Until Number of Elements is Less Than

Waits until the number of elements matching a locator is less than a specific count.

By listItemsLocator = By.className("list-item");
driver.element().waitUntilNumberOfElementsToBeLessThan(listItemsLocator, 10);

Wait Until Number of Elements is More Than

Waits until the number of elements matching a locator is more than a specific count.

By listItemsLocator = By.className("list-item");
driver.element().waitUntilNumberOfElementsToBeMoreThan(listItemsLocator, 0);

Wait Until Presence of All Elements

Waits until all elements matching the locator are present in the DOM (not necessarily visible).

By elementsLocator = By.className("data-row");
driver.element().waitUntilPresenceOfAllElementsLocatedBy(elementsLocator);

Getting Table Data

  • Extracts the data of a table's rows into a List of Map Objects
List<Map<String,String>> tableRowsData = driver.element().getTableRowsData(tableLocator);
  • the key of each Map objects represents the label of each column which is represented in the th tag in thead tag in a table
  • Note that this will only work with standard html tables and may not get the correct result if the table does not follow the standard html table:
<table>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>x</td><td>y</td><td>z</td></tr>
</tbody>
</table>
  • Using getTableRowsData on the table above will return the following List:
[
{"col1":"a", "col2":"b", "col3":"c"},
{"col1":"x", "col2":"y", "col3":"z"}
]