skip to content

Element Interaction

What you can actually do to an element once you hold it: click it, type into it, read its state, drive it with low-level input, and read the exception when the command cannot land.

on this pageshow

explore

questions

page 1 of 2

In Selenium, which class performs a hover or a right-click, and what call actually runs it?

level: juniorimportance: must knowfreq 76%

answer

  1. One builder class for pointer gestures
  2. Constructed from the driver, then chained
  3. moveToElement hovers, contextClick right-clicks
  4. The chain is inert until one final call
  5. perform() is what sends the sequence

basics

~10 s

Selenium's Actions class builds them: moveToElement for a hover, contextClick for a right-click, plus doubleClick, clickAndHold, release and dragAndDrop. Nothing reaches the browser until you call perform() on the chain.

solid answer

~40 s

You build the gesture with `org.openqa.selenium.interactions.Actions`, constructed from the driver, and run it with `perform()`. `moveToElement(el)` hovers by moving the pointer to the element's in-view centre; `contextClick(el)` right-clicks it; `doubleClick(el)` double-clicks; `clickAndHold(el)` presses without releasing and `release(el)` lets go; `dragAndDrop(source, target)` and `dragAndDropBy(source, x, y)` wrap hold-move-release for you. Each method returns the same builder, so the calls chain: `new Actions(driver).moveToElement(row).contextClick().perform()`. The classic beginner bug is omitting `perform()` - the chain is collected in memory and silently never sent, so the test fails later on the assertion rather than at the gesture. A second trap is reusing one `Actions` object for two gestures: `build()` empties the builder, so the second `perform()` sends nothing.

code

java · 19 lines
java
WebDriver driver = new ChromeDriver();
driver.get("https://reports.example.com/approvals");

WebElement row = driver.findElement(By.cssSelector("[data-report-id='EXP-4471']"));
WebElement approvedBucket = driver.findElement(By.id("approved-bucket"));
Actions actions = new Actions(driver);

actions.moveToElement(row).perform();

actions.contextClick(row).perform();

actions.doubleClick(row).perform();

actions.clickAndHold(row)
        .moveToElement(approvedBucket)
        .release()
        .perform();

driver.quit();

go deeper

for a junior

Name the Actions class, the method for each gesture, and the fact that perform() runs the chain. Being able to write a hover then a right-click from memory is the bar here.

for a middle

Explain that the convenience methods expand into pointer primitives, and that a manual hold, move and release is the same thing as dragAndDrop. Know why a missing perform() fails silently.

for a senior

Show judgment about when a hand-built sequence is warranted at all, and how you diagnose a drag that does nothing rather than blindly adding offsets and pauses to the chain.

for a principal

Own the cost question: pointer sequences are the least portable part of a suite, so decide where the team accepts them and where the application should expose a simpler path.

## The class, and the shape of a chain Every pointer or keyboard gesture that is more than a plain click lives on `org.openqa.selenium.interactions.Actions` in Selenium 4. You construct it with the driver, chain the steps you want, and call `perform()`: ```java new Actions(driver).moveToElement(reportRow).contextClick().perform(); ``` On an expense-report approval list that one line hovers a report row so its inline toolbar renders, then opens the row's right-click menu. Every method on the chain returns the same `Actions` object, which is what makes the chaining read the way it does. ## The convenience methods You almost never build raw pointer primitives yourself. `Actions` wraps them: | Method | What it does | |---|---| | `moveToElement(el)` | Moves the pointer to the in-view centre of `el` - a hover | | `moveToElement(el, x, y)` | Moves to an offset from that centre point | | `contextClick(el)` | Moves to `el`, then presses and releases the right button | | `doubleClick(el)` | Moves to `el`, then presses and releases the left button twice | | `clickAndHold(el)` | Moves to `el` and presses the left button without releasing it | | `release(el)` | Moves to `el` and releases the left button | | `dragAndDrop(src, tgt)` | Hold on `src`, move to `tgt`, release | | `dragAndDropBy(src, x, y)` | Hold on `src`, move by an offset, release | | `keyDown(key)` / `keyUp(key)` | Presses or releases one modifier key | | `pause(Duration)` | Waits inside the sequence | The no-argument overloads - `contextClick()`, `doubleClick()`, `clickAndHold()`, `release()` - act **at the pointer's current position** rather than on an element. That is what lets you write a hand-built drag as `clickAndHold(row).moveToElement(bucket).release().perform()`, which is exactly what `dragAndDrop(row, bucket)` does for you. A few details are worth carrying around: - Every one of these methods expands into **pointer primitives** - a `pointerMove`, a `pointerDown`, a `pointerUp` - so `doubleClick(el)` is one move followed by two press-and-release pairs. - `moveToElement(el, x, y)` measures its offset from the element's **in-view centre point**, not from its top left corner, so `(0, 0)` is the centre. - `dragAndDropBy(src, x, y)` moves by an offset **from where the pointer already is** after the press, so the numbers are relative, not page coordinates. - `keyDown(el, key)` and `keyUp(el, key)` click the element first to focus it, then press or release the key on the keyboard device. - `pause(long)` and `pause(Duration)` both exist and wait **inside** the sequence, so the driver paces the gesture rather than your test thread. ## perform() is not optional The single most common beginner mistake with this API is building a chain and never running it: ```java Actions actions = new Actions(driver); actions.moveToElement(reportRow).contextClick(); // nothing happened ``` `Actions` collects steps in memory; nothing reaches the browser until `perform()` (or `build()` followed by performing the returned `Action`). Because no request was ever made, the test does not throw - it simply carries on and fails later, on the assertion that expected the context menu. So when a gesture "does nothing", work through this order: 1. Check that the chain ends in `perform()`. 2. Check that this `Actions` object has not already been performed once. 3. Only then start suspecting the page. There is a second, quieter version of the same trap. `build()` empties the builder as it snapshots the sequences, and `perform()` calls `build()`, so running the same `Actions` object twice does **not** repeat the gesture: the second call sends an empty action set. Build a fresh chain for each gesture. ## Drag and drop, and where it stops working `dragAndDrop(source, target)` is a convenience for four steps on the virtual pointer: move to the source, press, move to the target, release. That is a **pointer-level** gesture, and pages that implement dragging by listening to pointer or mouse movement respond to it normally. A page that instead implements dragging through the browser's native HTML5 drag-and-drop API is a different mechanism, and a synthesized pointer sequence may not drive it. The event model behind that API is a browser-platform subject rather than a Selenium one; the practical Selenium-side point is only that `dragAndDrop` failing on a list that a human can clearly drag is a known shape of problem, not a mistake in your chain. Confirm which mechanism the approval list uses before you spend an afternoon tuning offsets. ## Element-targeted versus current-position overloads Choosing between `contextClick(row)` and `moveToElement(row).contextClick()` is usually taste - they build the same interactions. The difference appears once you need something in between: - `moveToElement(row).pause(Duration.ofMillis(300)).contextClick().perform()` gives a hover-triggered menu time to render before the right-click lands. - `clickAndHold(row).moveByOffset(0, 40).moveToElement(bucket).release().perform()` nudges the pointer first, which some drag implementations need before they treat the gesture as a drag at all. Both are ordinary chains. What makes them work is that each step is queued, the whole queue is sent once, and the browser replays it in order.

  • What is the difference between contextClick(element) and moveToElement(element).contextClick()?
    Almost nothing - the first is a convenience for the second, and both build a pointer move followed by a right button press and release. The difference only matters when you want something between the two, such as a `pause` that lets a hover-triggered menu render before the right-click lands.
  • Your dragAndDrop call does nothing on a list a human can clearly drag. What do you check first?
    Which drag mechanism the page uses. `dragAndDrop` synthesizes a pointer press, move and release, which drives pages that listen to pointer movement; a page built on the browser's native HTML5 drag-and-drop API is a different event model and may not respond. Confirm that before tuning offsets or durations.
  • Why can reusing the same Actions object for two gestures run only the first?
    `perform()` calls `build()`, and `build()` clears the builder's sequences as it snapshots them into a composite action. The second `perform()` therefore finds an empty set and sends an effectively empty command. Construct a new `Actions` for each gesture, or re-chain the steps before performing again.

saying these in an interview costs you the question

  • Builds an Actions chain and never calls perform()
  • Thinks hovering needs injected script rather than moveToElement
  • Reuses one Actions object for several gestures and expects each to run
  • Assumes dragAndDrop drives every draggable list on every page
  • Confuses contextClick with a plain left click on the element
open as a page

In Selenium, what does ElementClickInterceptedException mean, and what does its message name?

level: juniorimportance: must knowfreq 74%

basics

~20 s

The click target is covered: another element sits over its centre point and would receive the click. The driver's message names that intercepting element, usually its opening tag with id and class, so read it.

open as a page

In Selenium, how does the string given to JavascriptExecutor.executeScript run, and how do you get a value back?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Selenium runs the string as the body of an anonymous function in the current frame, so you need an explicit return to get a value; without one you get null. Values passed after the script appear as arguments[0], arguments[1].

open as a page

In Selenium, which three methods does the Select class offer to choose an option, and what does each match?

level: juniorimportance: must knowfreq 82%

basics

~10 s

Selenium's Select class offers selectByVisibleText, which matches an option's rendered text; selectByValue, which matches its value attribute exactly; and selectByIndex, which matches its zero-based position. Each throws NoSuchElementException when nothing matches.

open as a page

In Selenium, which Java types may be passed to executeScript, and what types can its result be?

level: middleimportance: must knowfreq 62%

basics

~20 s

You may pass numbers, booleans, strings, WebElements, and lists or String-keyed maps of those; anything else throws IllegalArgumentException. Results come back as Boolean, Long, Double, String, List, Map, WebElement or null, and always need a cast.

open as a page

Why does Selenium's Select class throw UnexpectedTagNameException on a dropdown built from div elements?

level: middleimportance: must knowfreq 68%

basics

~20 s

Selenium's Select constructor reads the element's tag name and accepts only a select tag. A styled listbox made of div and span elements has no option children and no multiple attribute, so the wrapper rejects it at construction.

open as a page

In Selenium, why does a page-object field holding a WebElement found in the constructor go stale?

level: middleimportance: must knowfreq 60%

basics

~20 s

The field lives as long as the page object while the node lives only until the next re-render. The constructor mints one reference, so the first redraw kills that field for the rest of the object's life.

open as a page

In Selenium, how does a stale element caused by a grid re-render differ from one caused by leaving the page?

level: middleimportance: must knowfreq 72%

basics

~20 s

A re-render detaches one node while the document stays live, so re-finding on the same page works. A navigation replaces the whole document, so every earlier reference dies at once and only the new page can supply one.

open as a page

In Selenium 4, how do WebElement.getDomAttribute and getDomProperty differ, and where does getAttribute fit?

level: middleimportance: must knowfreq 76%

basics

~20 s

getDomAttribute reads the value the page's HTML declared. getDomProperty reads the element's live DOM property, so it sees what the user typed or ticked. getAttribute is the older combined call: it prefers the property and falls back to the attribute.

open as a page

After a Ctrl+click Actions chain in Selenium, later steps in the same session misbehave. Why, and what clears it?

level: seniorimportance: must knowfreq 46%

basics

~20 s

Selenium's Actions never releases a modifier for you. A keyDown with no matching keyUp leaves the key depressed in the driver's input state, which outlives the chain and any new Actions object. Release it with keyUp, sendKeys(Keys.NULL), or resetInputState.

open as a page

In Selenium, how do you use the element named in an element click intercepted message to find the cause?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Read the interceptor's tag out of the message, then find that element in the application and ask why it was there at that moment. Its identity separates fixed page chrome, a leftover toast, and an open dialog.

open as a page

What changes in Selenium's Select class when the wrapped select element carries the multiple attribute?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Selecting by text or value stops selecting every match instead of just the first, the whole deselect family becomes legal, and isMultiple reports true. Selenium's Select reads that attribute once, in the constructor, and caches the answer.

open as a page

In Selenium, why can catching StaleElementReferenceException and retrying the same WebElement never succeed?

level: seniorimportance: must knowfreq 56%

basics

~20 s

The instance is bound to one reference the browser has already declared dead, and Selenium documents that all future calls on it fail. Recovery needs a new lookup, and a repeated write needs proof the first one did not land.

open as a page

In Selenium, what does WebElement.isDisplayed() actually compute, and why is it not normatively specified?

level: seniorimportance: must knowfreq 61%

basics

~20 s

It runs a bundled Selenium script that approximates visibility by walking the element tree: display none, visibility hidden, zero opacity, zero size and unscrollable overflow all make it false. The W3C specification only recommends this approach in an appendix.

open as a page

In Selenium, how do you choose between Keys.ENTER, clicking the submit button, and WebElement.submit()?

level: principalimportance: must knowfreq 46%

basics

~20 s

Click the real control by default, press Enter when the case covers the keyboard journey, and avoid submit. In Selenium 4 submit runs an injected script, so it skips every scroll and interactability check the click command performs.

open as a page

How would you move a large Selenium 4 suite off getAttribute onto getDomAttribute and getDomProperty?

level: principalimportance: must knowfreq 52%

basics

~20 s

Treat it as a semantic audit, not a rename. Group call sites by the name being read, move markup-only names first, turn boolean flags into isSelected and isEnabled, change live-value reads last, then ban the old call.

open as a page

In Selenium, how do you upload a local file through an input type=file element on a page?

level: juniorimportance: should knowfreq 68%

basics

~10 s

Find the input type=file element and send it the file's absolute path with sendKeys. Selenium sets the file directly on the input and never opens or drives the operating system's file-chooser dialog.

open as a page

In Selenium, what does StaleElementReferenceException tell you about a WebElement your test found earlier?

level: juniorimportance: should knowfreq 68%

basics

~20 s

It means the node that handle points at is no longer part of the page the browser is showing. Selenium re-checks the reference before every element command, so that handle is dead and the element has to be found again.

open as a page

In Selenium, what does calling perform() on an Actions chain send, and how are its ticks ordered?

level: middleimportance: should knowfreq 54%

basics

~20 s

Actions collects each step into a per-device sequence, and perform() posts them all as one WebDriver actions command. Steps sharing a tick run together across devices, and the browser waits for that tick's longest duration before the next one.

open as a page

In Selenium, what scrolling does WebElement.click() perform before clicking, and when does it skip it?

level: middleimportance: should knowfreq 52%

basics

~20 s

It calls scrollIntoView with instant behaviour, block end and inline nearest, so the bottom of the element is aligned with the bottom of the viewport. It skips the scroll when the element is already in view.

open as a page

In Selenium, why does WebElement.sendKeys append rather than replace an input's existing value?

level: middleimportance: should knowfreq 66%

basics

~20 s

Send Keys never resets the field. When the input is not already focused the driver focuses it and puts the caret after the existing text, then types character by character, so the new characters land on the end.

open as a page

In Selenium 4, how do ElementClickInterceptedException and ElementNotInteractableException differ and relate?

level: middleimportance: should knowfreq 54%

basics

~20 s

Interception means something is painted over the target. Not-interactable means the target itself cannot be reached at all: not rendered, not scrollable into view, or not focusable for typing. In Selenium 4 the intercepted class extends the not-interactable one.

open as a page

In Selenium, how does the Select class actually change which option of a dropdown is selected?

level: middleimportance: should knowfreq 47%

basics

~20 s

It clicks the option element. Selenium's Select checks the option is enabled, compares its current selectedness with the state you asked for, and clicks only when they differ, so re-selecting an already-chosen option sends nothing at all.

open as a page

In Selenium, why can WebElement.getText() return an empty string for an element whose markup has text?

level: middleimportance: should knowfreq 67%

basics

~20 s

Because it returns rendered text, not markup text. Anything the browser did not draw contributes nothing, so an element hidden by display none or visibility hidden yields an empty string even though its characters are in the page.

open as a page

In Selenium, why can clear() empty a framework-controlled input yet leave the app using the old text?

level: seniorimportance: should knowfreq 47%

basics

~20 s

Clear resets the value through the HTML clear algorithm and dispatches no key events at all. A component that keeps its own copy of the field's value and updates it from typing can miss the reset, so its copy stays stale.

open as a page

In Selenium, where on an element does WebElement.click() actually land, and how is that point computed?

level: seniorimportance: should knowfreq 41%

basics

~10 s

Selenium clicks the in-view centre point: the centre of the intersection between the element's first client rectangle and the viewport, floored to whole pixels. Whatever is painted at that one coordinate receives the click.

open as a page

A Selenium upload passes locally but the remote browser cannot find the file - why, and what fixes it?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Java's RemoteWebDriver starts with a UselessFileDetector, so sendKeys forwards your local path as plain text and the browser's own machine has no such file. Call setFileDetector with a LocalFileDetector so the client ships the file first.

open as a page

Why can Selenium's Actions.moveToElement raise MoveTargetOutOfBoundsException where WebElement.click() does not?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Element Click scrolls the target into view before acting; a pointer move does not. Actions computes the element's in-view centre point plus your offsets and fails when the result lands outside the viewport.

open as a page

In Selenium, why does forcing a tax-return page's Submit button with executeScript("arguments[0].click()", el) hide a real defect?

level: seniorimportance: should knowfreq 58%

basics

~20 s

The injected click fires straight at the node, so it works even when a banner covers the button or the button is invisible. The test goes green while a real user, whose pointer hits whatever sits on top, cannot submit.

open as a page

In Selenium, what do Select's getOptions and getAllSelectedOptions return, and what does each call cost?

level: seniorimportance: should knowfreq 44%

basics

~20 s

getOptions runs a fresh search for the select's option elements and returns a snapshot list, not a live collection. getAllSelectedOptions filters that list by asking each option whether it is selected, so it costs one find plus one command per option.

open as a page

showing 1–30 of 36