NoSuchElementException
NoSuchElementException: Causes and Fixes
Fix Selenium NoSuchElementException (NoSuchElementError in JS): timing, wrong locators, iframes, shadow DOM and windows, with fixes in Java, Python, JS and C#.
| Java | org.openqa.selenium.NoSuchElementException |
|---|---|
| Python | selenium.common.exceptions.NoSuchElementException |
| JavaScript | NoSuchElementError |
| C# | OpenQA.Selenium.NoSuchElementException |
What the error means
findElement asked the browser for an element matching your locator and the browser answered “no such element”. The search ran against the current browsing context only (the active window and frame), at one instant in time. If nothing matched at that instant, the driver throws.
That definition explains almost every case: the element did not exist yet, the locator does not match what is actually in the DOM, or the element lives somewhere the search did not look (an iframe, a shadow root, another tab).
Note that findElements (plural) never throws this error. It returns an empty list, which is the right tool when absence is a valid outcome.
What it looks like
// Javaorg.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#login"} (Session info: chrome=131.0.6778.86)For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exceptionBuild info: version: '4.52.0' at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:...)# Pythonselenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#login"} (Session info: chrome=131.0.6778.86); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception// JavaScript (selenium-webdriver)NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"#login"} (Session info: chrome=131.0.6778.86) at Object.throwDecodedError (node_modules/selenium-webdriver/lib/error.js:...)// C#OpenQA.Selenium.NoSuchElementException : no such element: Unable to locate element: {"method":"css selector","selector":"#login"} (Session info: chrome=131.0.6778.86)Firefox words it differently: Unable to locate element: #login. Note that By.id("login") shows up as css selector #login because the bindings translate ID, name and class locators into CSS.
Common causes
- The element is not there yet. The page or a component is still rendering, an XHR has not returned, or a click triggered navigation that has not completed.
- The locator is wrong. A typo, a dynamic ID (
btn_83412), a class that changed in a redesign, or an XPath copied from DevTools that depends on position. - The element is inside an iframe. The driver only searches the current frame.
- The element is inside a shadow root. Normal CSS and XPath searches do not cross shadow boundaries.
- You are in the wrong window or tab. A link opened a new tab and the driver is still pointed at the old one.
- The element only exists in a certain state. A responsive layout hides it at the headless default window size, or it only renders after hover, scroll or login.
How to fix it
The element is not there yet
Use an explicit wait for the condition you actually need. Do not add sleeps, and do not rely on a large implicit wait to paper over it.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));WebElement login = wait.until( ExpectedConditions.visibilityOfElementLocated(By.id("login")));login.click();from selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC
login = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, "login")))login.click()const { By, until } = require('selenium-webdriver');
const login = await driver.wait(until.elementLocated(By.id('login')), 10000);await driver.wait(until.elementIsVisible(login), 10000);await login.click();var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));IWebElement login = wait.Until(d =>{ var el = d.FindElement(By.Id("login")); return el.Displayed ? el : null;});login.Click();WebDriverWait ignores NoSuchElementException while polling in Java, Python and C#, so the lambda form is safe. If the wait times out you get a TimeoutException instead, which tells you the element never appeared within the budget.
The locator is wrong
Test the locator in DevTools before blaming timing. In the Elements panel press Ctrl+F (Cmd+F on macOS) and paste the CSS or XPath; the panel shows how many nodes match. Zero means the locator is wrong, more than one means it is ambiguous.
Prefer stable hooks: data-testid attributes, IDs that are not generated, name on form fields, or accessible text. Replace position-based XPath like /html/body/div[3]/div[2]/button with something anchored to meaning.
// Fragile: By.id("btn_83412")By submit = By.cssSelector("[data-testid='checkout-submit']");By byPrefix = By.cssSelector("button[id^='btn_']");By byText = By.xpath("//button[normalize-space()='Place order']");# Fragile: (By.ID, "btn_83412")submit = (By.CSS_SELECTOR, "[data-testid='checkout-submit']")by_prefix = (By.CSS_SELECTOR, "button[id^='btn_']")by_text = (By.XPATH, "//button[normalize-space()='Place order']")// Fragile: By.id('btn_83412')const submit = By.css("[data-testid='checkout-submit']");const byPrefix = By.css("button[id^='btn_']");const byText = By.xpath("//button[normalize-space()='Place order']");// Fragile: By.Id("btn_83412")By submit = By.CssSelector("[data-testid='checkout-submit']");By byPrefix = By.CssSelector("button[id^='btn_']");By byText = By.XPath("//button[normalize-space()='Place order']");The element is inside an iframe
Switch into the frame first, and wait for the frame itself to be available. Switch back with defaultContent() when done.
new WebDriverWait(driver, Duration.ofSeconds(10)).until( ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe#payment")));driver.findElement(By.name("cardnumber")).sendKeys("4242424242424242");driver.switchTo().defaultContent();WebDriverWait(driver, 10).until( EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe#payment")))driver.find_element(By.NAME, "cardnumber").send_keys("4242424242424242")driver.switch_to.default_content()await driver.wait(until.ableToSwitchToFrame(By.css('iframe#payment')), 10000);await driver.findElement(By.name('cardnumber')).sendKeys('4242424242424242');await driver.switchTo().defaultContent();var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));wait.Until(d =>{ d.SwitchTo().Frame(d.FindElement(By.CssSelector("iframe#payment"))); return true;});driver.FindElement(By.Name("cardnumber")).SendKeys("4242424242424242");driver.SwitchTo().DefaultContent();The element is inside a shadow root
Find the shadow host, get its shadow root, then search inside it with CSS. See NoSuchShadowRootException if the host has no open shadow root.
SearchContext shadow = driver.findElement(By.cssSelector("app-login")).getShadowRoot();shadow.findElement(By.cssSelector("#login")).click();shadow = driver.find_element(By.CSS_SELECTOR, "app-login").shadow_rootshadow.find_element(By.CSS_SELECTOR, "#login").click()const host = await driver.findElement(By.css('app-login'));const shadow = await host.getShadowRoot();await (await shadow.findElement(By.css('#login'))).click();ISearchContext shadow = driver.FindElement(By.CssSelector("app-login")).GetShadowRoot();shadow.FindElement(By.CssSelector("#login")).Click();You are in the wrong window or tab
If the click opened a new tab, wait for the handle count to change and switch to the new handle. The windows and tabs lesson and the switch to new tab recipe cover the full pattern.
The element only exists in a certain state
Headless Chrome starts at a small default size, so desktop-only navigation may be collapsed into a hamburger menu. Set an explicit window size (for example --window-size=1920,1080) so headless and headed runs see the same layout. For hover menus, perform the hover with the Actions API before searching.
How to prevent it
- Use explicit waits on every element that appears asynchronously, and keep the implicit wait at zero. Mixing the two makes timeouts unpredictable.
- Agree on
data-testidattributes with your developers. They survive redesigns. - Keep frame and window switching inside page objects so a test never searches in the wrong context.
- Use
findElements(...).isEmpty()when you need to check for absence rather than catching the exception. See the element exists recipe. - Take a screenshot and save
driver.getPageSource()on failure. Half the time the page shows an error banner or a login screen, not the page you expected.
Related errors
- TimeoutException: what you get when an explicit wait for the element gives up.
- StaleElementReferenceException: the element was found, then removed from the DOM.
- InvalidSelectorException: the locator is not even valid syntax.
- NoSuchFrameException: the frame you tried to switch into does not exist.
- NoSuchShadowRootException: the host element has no shadow root to search.
Go deeper
- Common Errors Diagnose and fix the most common Selenium errors and exceptions.
- Explicit Waits Learn to use explicit waits in Selenium to handle dynamic content and avoid flaky tests.
- Locator Strategy Guide A decision framework for choosing locators that survive UI changes: test IDs, the priority order, handling dynamic attributes, text-based lookups, uniqueness checks, and the anti-patterns that make suites brittle.
- iFrames and Frames Learn to switch between frames and iframes to interact with embedded content.