How to Find Elements by ID in Selenium

On This Page What is findElement by ID in SeleniumLocators in Seleni

May 24, 2026 · 8 min read · Tool Comparison

How to Find Elements by ID in Selenium

interacts with web elements on a webpage by situate them and so do actions like chatter, selecting, or entering schoolbook. The Selenium WebDriver interface offering two methods,, to identify elements on the page.

The findElement () method is used to place a single, unique web element, while findElements () is used to locate a list of web elements on the page.

What is findElement by ID in Selenium

WebDriver ’ s interface takes in the By object as a parameter and returns a web component objective. By object can be utilise with different locator strategies such as ID, gens class gens, link text, etc.

This web element later can be expend to perform actions like clicking, entering schoolbook, hovering on it, etc. You can use the findElement () along with the By.Id locator to situate an element utilise its id.

Locators in Selenium

are crucial for identifying elements on a web page.

Locators in Selenium

  1. ID
  2. Name
  3. Class Name
  4. Tag Name
  5. Link Text
  6. Partial Link Text
  7. XPath
  8. CSS Selectors

Each locator case has its own syntax and is suited for different scenarios based on the structure of the HTML and the attributes of the elements.

1. ID:Locates an component habituate its unique ID dimension. This is one of the fastest and well-nigh reliable locater eccentric.

2. Name:Finds elements by their name attribute. This can be useful when multiple constituent portion the same gens.

3. Class Name: Targets elements based on their category attribute. This is utile for selecting multiple elements that percentage a stratum.

4. Tag Name: Locates elements by their tag name (like, remark, button, div). This can be used to find all factor of a specific character.

5. Link Text: Specifically used to locate anchor (& lt; a & gt;) elements by their seeable text. This is helpful for finding tie-in.

6. Partial LinkText: Alike to Link Text, but allows for fond matching of the anchor text, making it useful for long or dynamic linkup text.

7. :A powerful and flexible locator that uses XML path language to navigate through elements and attributes in the DOM.

8. CSS Selector: Utilizes CSS selectors to find elements. This is often quicker than XPath and can be very expressive for complex selections.

Read More:

Why ID is a preferent locater for finding elements

ID is preferred over any other locator due to following reasons:

1. Unique: An id consort with the factor on the web page is typically unique which ensures that it locates a individual element solely. This reduces the danger of identifying multiple elements and makes it less error prone unlike other locators such as course gens which may locate multiple elements.

2. Unproblematic and easy to read: Id names are generally concise and straight making them uncomplicated to use in test book and easy to keep.

3. Speed and efficiency: Selenium WebDriver can quickly locate the element by using its ID. It is a much quicker access than utilize any other locator like form gens or XPath which may involve more complex structure. This makes ID the fastest and most efficient locator among all the other locators of Selenium WebDriver.

4. Stable and reliable: IDs are very rare to alter unlike other locater like CSS picker and class gens which may be dynamically generated or may change as the page updates. This makes the ID as the most stable and reliable locator as compared to the early locater.

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Syntax for Finding Elements by ID

WebElement elementName = driver.findElement (By.id (`` LocatorValue ''));
  • WebElementis the Selenium interface that represents the HTML factor on the web page which permit users to interact with the element.
  • driveris the WebDriver instance that controls the browser.
  • findElementis a method that is used to place a single element on the web page. If there are multiple elements matching the criteria, it will return the first matching element. If no element is found Selenium will cast NoSuchElementException.
  • Byis a course in Selenium used to place constituent in different ways.
  • By.id (“ LocatorValue ”)is the unique ID of the web element which you take to locate.
  • The ingredient variable is a reference to theWebElementfound by thefindElement () method.

Read More:

How to Find Element by ID in Selenium

Follow the steps below to regain an element by its ID employ the By.id () method

Prerequisites

1. Install Java Development Kit (JDK):

  • Before instal Selenium, make sure to download Java from the OracleDownload page.
  • Set the JAVA_HOME path variable in System ’ s environment variables.
  • Verify Java is install correctly by opening the bid prompting and run the bid as “ java -version ”.

2. Set Up the IDE: Set up and use Eclipse or IntelliJ as the editor for write Java codification.

3. Selenium WebDriver: Add Selenium Jars in the projection or add Selenium Java habituation if you are utilise a Maven undertaking

& lt; habituation & gt; & lt; groupId & gt; org.seleniumhq.selenium & lt; /groupId & gt; & lt; artifactId & gt; selenium-java & lt; /artifactId & gt; & lt; edition & gt; 4.27.0 & lt; /version & gt; & lt;! -- Choose the up-to-the-minute version -- & gt; & lt; /dependency & gt;

Code instance

public classGetElementById {WebDriver driver; @ Testpublic voidclickGetStartedFree ()throwsIOException {driver =newChromeDriver (); driver.get (`` https: //www.browserstack.com '');try{WebElement getStartedFree= driver.findElement (By.id(`` signupModalProductButton '')); getStartedFree.click (); Assert.assertTrue(driver.getCurrentUrl () .contains (`` sign_up ''));}catch(Exception e) {System.out.println (`` Assert neglect: `` +e.getStackTrace ());} driver.quit ();}}

Code explanation:

1. The findElement (By.id (& # 8220; signupModalProductButton & # 8221;))situate the Get Started ingredient with the id“ signupModalProductButton ”.

2. After the element is located, the button is clicked.

3. Finally, an assert is perform to verify the page URL.

When to use Finding Element by ID in Selenium

Finding an element by id is a highly effective and most used method for locating web elements. Following are some scenarios when you should use By.id () to locate elements.

  • When any element has a valid and unique ID, it is best to locate the factor by id. Finding an ingredient by id is the simplest and easiest method among all the other locater strategies. The complexness of the test code is reduced which is greater while creating locators via XPath and CSS selector.
  • Inactive and stable IDs: If the ID of the web element is motionless and does not change even after the page reloads, it is the most worthy method to locate the element. Even when the page reloads and the structure is changed, you do not hold to vex about breaking of the locator as the ID value will generally be consistent and unaltered.
  • Well-defined web pages: If you are working with a website that adheres to trump practices in terms of design and structure, most ingredient have well-defined and unique IDs. Working with such well-structured websites makes it ideal to locate the elements by their ID value.
  • Need Faster execution: Locating the web element by its ID is the fastest and about efficient method as IDs are unique. Typically, browsers use internal indexing for IDs which allow them to chop-chop locate the element in the DOM without the need of scanning the entire HTML papers.

Talk to an Expert

Best Practices when Finding Element by ID in Selenium

Follow below best practices when finding element by id to ensure that the examination are authentic, maintainable, and efficient

1. Use unique IDs: Ensure that the id attribute for the element to be located should be unique and descriptive across the page. Non-unique or duplication id for any component may conduct to inconsistent behaviour and flaky tryout execution.

2. Avoid using dynamic IDs: Generally, ID is unequaled for the factor on the web page, however for some web pages, the ID value may change on page reload or DOM review. For such scenarios, the ID is not the valid and reliable locator to use and you should combine it with former locator like XPath or CSS selectors to make the locater more robust.

3. Avoid insistent findElement () calls: If there is a need to interact with the same element multiple times, instead of calling findElement () every clip, store the web element reference and recycle it. Repeated DOM lookups are ineffective and slow down the test execution.

4. Use denotative waits: Implicit waits are the spheric postponement which may lead to unpredictable results and therefore, explicit waits should be used which allows you to wait for the specific weather before proceeding for any action to avoid any exception.

If Selenium tries to interact with an element that is not completely loaded, it may throw an. Therefore, to avoid such exceptions it is always a good pattern to use explicit waits wherever potential.

Read More:

5. Use combination of IDs with other attributes: Sometimes, ID solely can be insufficient to locate alone elements on the web page. When the id is equivocal, deal combining ID with early locators such as stratum name, name, or CSS chooser to create more robust and stable locater.

6. Test on multiple browsers: Locating elements by ID is the virtually reliable and effective way. However, it is advisable to test your Selenium scripts on multiple browsers like Chrome, Firefox, Safari, etc. to secure that it functions consistently across all browser without any discrepancies or differences.

Use program like BrowserStack Automate to screen on real browsers and devices. provides access to 3500+ existent device and browsers to test under.

allows you to run Selenium tests on multiple devices and browser combinations parallelly to save time, while maximizing coverage.

Conclusion

FindElement by ID is the simplest and fastest way to site web elements on the web page. You would hold a solid foundation for automating web applications by surmount how to bump ingredient by ID in Selenium.

is the # 1 choice among the web mechanization testers for creating robust and stable automation scripts and likewise BrowserStack is the # 1 Cloud program which testers could use to run their tests on 3500+ devices, browser and platforms!

If you are eager to get your web automation journey, try exploring to help you in your automation journey by sign in today!

Tags
86,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free