Popular Searches
Popular Course Categories
Popular Courses

Name Locator

Selenium Locators

Name Locator in Selenium

The Name Locator is one of the standard locator strategies provided by Selenium WebDriver for identifying web elements through the value of their HTML name attribute. It is commonly used for locating form fields such as username, password, email, search boxes, radio buttons, checkboxes, and other input elements.

In Selenium Java, the Name Locator is implemented using By.name(). For example, if an HTML element contains name="username", Selenium can locate it using driver.findElement(By.name("username")).

Locators are an important part of Selenium WebDriver because automation scripts need to identify the correct WebElement before performing actions such as click(), sendKeys(), clear(), getText(), or attribute validation. JustAcademy's Selenium training curriculum includes locating elements using strategies such as ID, XPath, and CSS selectors as part of Selenium WebDriver and WebElement automation. :contentReference[oaicite:0]{index=0}

Learn more through the JustAcademy's Selenium Training Course and explore the Selenium Course Demo Registration.


1. What is a Name Locator?

A Name Locator is a Selenium locator strategy that identifies a web element using the value of its HTML name attribute.

The basic Selenium Java syntax is:

driver.findElement(By.name("elementName"));

For example, consider this HTML:

<input type="text" name="username">

The element can be located using:

driver.findElement(By.name("username"));

Here, username is the value of the name attribute.


2. Understanding the HTML name Attribute

The name attribute is an HTML attribute commonly used to identify form controls and associate submitted form values with field names.

Example:

<input type="text" name="firstName">

In this example:

  • input is the HTML element.
  • type is an HTML attribute.
  • text is the value of the type attribute.
  • name is the attribute used by Selenium for the Name Locator.
  • firstName is the name attribute value.


3. Syntax of Name Locator

The Selenium Java syntax for a Name Locator is:

By.name("nameValue")

It is generally used with findElement():

WebElement element = driver.findElement(By.name("nameValue"));

For example:

WebElement username = driver.findElement(By.name("username"));


4. Simple Name Locator Example

Suppose a web page contains the following input field:

<input type="text" name="username">

Selenium code:

driver.findElement(By.name("username")).sendKeys("admin");

Selenium first searches for an element whose name attribute has the value username and then enters the specified text.


5. Name Locator with Username Field

<input type="text" name="username" placeholder="Enter Username">

Selenium:

driver.findElement(By.name("username")).sendKeys("john");


6. Name Locator with Password Field

<input type="password" name="password" placeholder="Enter Password">

Selenium:

driver.findElement(By.name("password")).sendKeys("Pass@123");


7. Name Locator with Email Field

<input type="email" name="email">

Selenium:

driver.findElement(By.name("email")).sendKeys("[email protected]");


8. Name Locator with Search Box

<input type="search" name="search">

Selenium:

driver.findElement(By.name("search")).sendKeys("Selenium WebDriver");


9. Name Locator with Button

A button can also have a name attribute.

<button type="submit" name="login">Login</button>

Selenium:

driver.findElement(By.name("login")).click();


10. Name Locator with Checkbox

<input type="checkbox" name="terms" value="accepted">

Selenium:

WebElement terms = driver.findElement(By.name("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}


11. Name Locator with Radio Button

<input type="radio" name="gender" value="male">

<input type="radio" name="gender" value="female">

Because both radio buttons belong to the same group, they can share the same name.

List<WebElement> genderOptions = driver.findElements(By.name("gender"));


12. Name Locator with Form Fields

Name locators are particularly common in HTML forms.

<form>

    <input type="text" name="firstName">

    <input type="text" name="lastName">

    <input type="email" name="email">

    <input type="password" name="password">

</form>

Selenium:

driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");


13. Name Locator with sendKeys()

The sendKeys() method is used to enter text into an input element.

driver.findElement(By.name("username")).sendKeys("admin");

This is commonly used for username, email, password, address, search, and other text fields.


14. Name Locator with clear()

The clear() method removes the existing value from a text input.

driver.findElement(By.name("username")).clear();

A common pattern is:

WebElement username = driver.findElement(By.name("username"));

username.clear();

username.sendKeys("newUser");


15. Name Locator with click()

The click() method can be used when the located element is clickable.

driver.findElement(By.name("login")).click();

It can be used for buttons, checkboxes, radio buttons, links, and other interactive elements when their name attribute is suitable.


16. Name Locator with getText()

The getText() method retrieves visible text from an element.

String message = driver.findElement(By.name("message")).getText();

System.out.println(message);

The element must have the corresponding name attribute.


17. Name Locator with getAttribute()

The getAttribute() method can be used to retrieve attribute values.

WebElement username = driver.findElement(By.name("username"));

 

String value = username.getAttribute("value");

System.out.println(value);


18. Name Locator with WebElement

The located element can be stored in a WebElement variable.

WebElement emailField = driver.findElement(By.name("email"));

emailField.sendKeys("[email protected]");

This approach is useful when the same element needs to be accessed multiple times.


19. Required Selenium Imports

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;


20. Complete Basic Name Locator Program

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class NameLocatorExample {

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.name("username")).sendKeys("admin");

        driver.findElement(By.name("password")).sendKeys("admin123");

        driver.findElement(By.name("login")).click();

 

        driver.quit();

    }

}


21. Name Locator in Login Form

Consider the following login form:

<form>

    <input type="text" name="username">

    <input type="password" name="password">

    <button type="submit" name="login">Login</button>

</form>

Selenium automation:

driver.findElement(By.name("username")).sendKeys("admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.name("login")).click();


22. Name Locator in Registration Form

<input type="text" name="firstName">

<input type="text" name="lastName">

<input type="email" name="email">

<input type="password" name="password">

<input type="password" name="confirmPassword">

<button type="submit" name="register">Register</button>

Selenium:

driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");

driver.findElement(By.name("confirmPassword")).sendKeys("Pass@123");

driver.findElement(By.name("register")).click();


23. Name Locator in Search Form

<input type="text" name="query">

<button type="submit" name="search">Search</button>

driver.findElement(By.name("query")).sendKeys("Laptop");

driver.findElement(By.name("search")).click();


24. Name Locator for Checkboxes

Checkboxes can use the same name when they represent a group of related options.

<input type="checkbox" name="skills" value="java">

<input type="checkbox" name="skills" value="selenium">

<input type="checkbox" name="skills" value="sql">

To locate all matching checkboxes:

List<WebElement> skills = driver.findElements(By.name("skills"));

 

System.out.println("Number of skills: " + skills.size());


25. Name Locator for Radio Button Groups

Radio buttons commonly share the same name value because the name groups them together.

<input type="radio" name="payment" value="card">

<input type="radio" name="payment" value="upi">

<input type="radio" name="payment" value="cash">

All radio buttons can be located using:

List<WebElement> paymentOptions = driver.findElements(By.name("payment"));


26. Selecting a Radio Button by Name and Value

Because multiple radio buttons can share the same name, the name locator alone may return multiple elements.

List<WebElement> options = driver.findElements(By.name("payment"));

 

for (WebElement option : options) {

    if ("upi".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}


27. Name Locator with findElement()

findElement() returns one matching WebElement.

WebElement username = driver.findElement(By.name("username"));

If no matching element exists, Selenium can throw NoSuchElementException.


28. Name Locator with findElements()

findElements() returns a list of matching WebElements.

List<WebElement> elements = driver.findElements(By.name("username"));

If no matching elements are found, findElements() returns an empty list.


29. Difference Between findElement() and findElements()

FeaturefindElement()findElements()
Return TypeWebElementList<WebElement>
Multiple MatchesReturns first matching elementReturns all matching elements
No MatchThrows NoSuchElementExceptionReturns empty list
Typical UseSingle fieldGroups of elements


30. Name Locator with Multiple Elements

Suppose a page contains:

<input type="text" name="username">

<input type="text" name="username">

<input type="text" name="username">

Using:

driver.findElement(By.name("username"));

will locate the first matching element.

Using:

driver.findElements(By.name("username"));

will return all matching elements.


31. Checking the Number of Elements

List<WebElement> fields = driver.findElements(By.name("username"));

 

System.out.println("Count: " + fields.size());

This can be useful when testing repeated fields or grouped controls.


32. Name Locator and Unique Values

A Name Locator works particularly well when the target element has a meaningful and stable name attribute.

<input type="email" name="emailAddress">

Selenium:

driver.findElement(By.name("emailAddress")).sendKeys("[email protected]");


33. Name Attribute Does Not Always Mean Unique Element

Unlike an ID, the same name value can legitimately appear on multiple elements. This is especially common with radio buttons and groups of checkboxes.

<input type="radio" name="gender" value="male">

<input type="radio" name="gender" value="female">

Both elements have the same name.


34. Name Locator vs ID Locator

FeatureID LocatorName Locator
Java SyntaxBy.id("value")By.name("value")
HTML Attributeidname
Typical UseUnique elementsForm elements and grouped controls
Can Be SharedIDs are intended to be uniqueName values can be shared
Multiple MatchesUsually unexpectedCommon in groups


35. Name Locator vs Class Name Locator

FeatureNameClass Name
Attributenameclass
Selenium MethodBy.name()By.className()
Common UseForm controlsStyling/grouping
Examplename="email"class="input-field"


36. Name Locator vs Tag Name

FeatureName LocatorTag Name
MethodBy.name()By.tagName()
Usesname attributeHTML tag
Examplename="username"input


37. Name Locator vs XPath

FeatureName LocatorXPath
SyntaxBy.name("username")By.xpath("//input[@name='username']")
ComplexitySimpleCan be simple or complex
Text MatchingNo direct supportSupported
RelationshipsNoYes
Best UseStable name attributeComplex element identification


38. Name Locator vs CSS Selector

A CSS attribute selector can locate an element using its name attribute.

driver.findElement(By.cssSelector("[name='username']"));

The direct Name Locator is:

driver.findElement(By.name("username"));


39. Name Locator with CSS Attribute Selector

CSS selectors can also be used when additional attributes need to be included.

driver.findElement(

    By.cssSelector("input[name='username']")

);

This identifies an input element whose name attribute is username.


40. Name Locator with XPath

The equivalent XPath can be:

driver.findElement(By.xpath("//input[@name='username']"));

When only a stable name is required, By.name() provides a simpler syntax.


41. Dynamic Name Attributes

Some applications generate dynamic values for the name attribute.

<input name="user_12345" type="text">

On another execution, it might become:

<input name="user_98765" type="text">

A locator using the complete changing value may become unreliable.


42. Handling Dynamic Name Attributes

When the name changes dynamically, inspect the element for another stable attribute.

<input name="user_12345" id="username" type="text">

If the ID is stable, use:

driver.findElement(By.id("username"));

Other alternatives can include CSS selectors or XPath depending on the HTML structure.


43. Name Locator with Explicit Wait

When a name-based element is loaded dynamically, an explicit wait can be used.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement username = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("username")

    )

);

 

username.sendKeys("admin");


44. Name Locator with ElementToBeClickable

For a button identified by name:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement login = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.name("login")

    )

);

 

login.click();


45. Required Wait Imports

import java.time.Duration;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;


46. Name Locator and Iframes

If an element is inside an iframe, Selenium must switch to the correct iframe before using the Name Locator.

WebElement frame = driver.findElement(By.id("loginFrame"));

driver.switchTo().frame(frame);

 

driver.findElement(By.name("username")).sendKeys("admin");

 

driver.switchTo().defaultContent();


47. Name Locator and Windows or Tabs

If the required element is present in another browser window or tab, switch to that window before locating the element.

String originalWindow = driver.getWindowHandle();

 

for (String window : driver.getWindowHandles()) {

    if (!window.equals(originalWindow)) {

        driver.switchTo().window(window);

        break;

    }

}

 

driver.findElement(By.name("username")).sendKeys("admin");


48. Name Locator and Shadow DOM

Elements inside a Shadow DOM may require Shadow Root handling. Simply using By.name() from the document context may not locate an element inside a shadow tree.

The correct strategy depends on the application's Shadow DOM implementation and the WebDriver APIs being used.


49. Name Locator and Dynamic Web Applications

Modern web applications can create or update elements dynamically. An element may have a valid name but may not be present when Selenium first searches for it.

In such situations, synchronization should be considered:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement email = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("email")

    )

);

 

email.sendKeys("[email protected]");


50. Name Locator with AJAX Content

If an AJAX request adds a form field after the page loads, Selenium may need to wait for the field.

WebElement search = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("search")

    )

);

 

search.sendKeys("Selenium");


51. Name Locator for Multiple Checkboxes

<input type="checkbox" name="hobby" value="reading">

<input type="checkbox" name="hobby" value="coding">

<input type="checkbox" name="hobby" value="travel">

Locate all checkboxes:

List<WebElement> hobbies = driver.findElements(By.name("hobby"));


52. Selecting a Specific Checkbox by Value

List<WebElement> hobbies = driver.findElements(By.name("hobby"));

 

for (WebElement hobby : hobbies) {

    if ("coding".equals(hobby.getAttribute("value"))) {

        if (!hobby.isSelected()) {

            hobby.click();

        }

        break;

    }

}


53. Selecting a Specific Radio Button by Value

List<WebElement> paymentOptions = driver.findElements(By.name("payment"));

 

for (WebElement option : paymentOptions) {

    if ("card".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}


54. Name Locator for Select Elements

A standard HTML select element can have a name attribute.

<select name="country">

    <option value="india">India</option>

    <option value="usa">USA</option>

</select>

The select element can be located using:

WebElement country = driver.findElement(By.name("country"));

The Selenium Select class can then be used to select an option.

Select select = new Select(country);

select.selectByValue("india");


55. Name Locator for Dropdowns

Complete example:

WebElement countryElement = driver.findElement(By.name("country"));

 

Select country = new Select(countryElement);

country.selectByVisibleText("India");


56. Import for Select Class

import org.openqa.selenium.support.ui.Select;


57. Name Locator for Textarea

A textarea can also have a name attribute.

<textarea name="address"></textarea>

Selenium:

driver.findElement(By.name("address"))

      .sendKeys("Mumbai, Maharashtra");


58. Name Locator for File Upload

<input type="file" name="resume">

Selenium:

driver.findElement(By.name("resume"))

      .sendKeys("C:\\files\\resume.pdf");

For file upload controls, sendKeys() can be used to provide the file path when the control supports direct file selection.


59. Name Locator for Hidden Inputs

<input type="hidden" name="token" value="ABC123">

Selenium may locate the element:

WebElement token = driver.findElement(By.name("token"));

System.out.println(token.getAttribute("value"));

However, hidden elements are generally not directly interactable like visible form controls.


60. Name Locator for Error Messages

<span name="emailError">Invalid email</span>

Selenium:

String error = driver.findElement(By.name("emailError")).getText();

System.out.println(error);


61. Name Locator for Success Messages

<div name="successMessage">Registration successful</div>

Selenium:

String message = driver.findElement(By.name("successMessage")).getText();

System.out.println(message);


62. Name Locator and isDisplayed()

WebElement message = driver.findElement(By.name("successMessage"));

 

if (message.isDisplayed()) {

    System.out.println("Message is displayed.");

}


63. Name Locator and isEnabled()

WebElement submit = driver.findElement(By.name("submit"));

 

if (submit.isEnabled()) {

    System.out.println("Submit button is enabled.");

}


64. Name Locator and isSelected()

This method is particularly useful for checkboxes and radio buttons.

WebElement option = driver.findElement(By.name("gender"));

 

System.out.println(option.isSelected());

When multiple radio buttons share the same name, use findElements() and inspect each element.


65. Complete State Validation

WebElement checkbox = driver.findElement(By.name("terms"));

 

System.out.println("Displayed: " + checkbox.isDisplayed());

System.out.println("Enabled: " + checkbox.isEnabled());

System.out.println("Selected: " + checkbox.isSelected());


66. Name Locator and Forms

Name locators are especially useful in form automation because many form controls naturally contain name attributes.

<form>

    <input name="firstName">

    <input name="lastName">

    <input name="email">

    <textarea name="address"></textarea>

    <button name="submit">Submit</button>

</form>


67. Complete Form Automation with Name Locators

driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("address")).sendKeys("Mumbai, Maharashtra");

driver.findElement(By.name("submit")).click();


68. Name Locator in Page Object Model

In the Page Object Model, Name Locators can be stored as private fields.

public class LoginPage {

 

    private WebDriver driver;

 

    private By username = By.name("username");

    private By password = By.name("password");

    private By loginButton = By.name("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(String user, String pass) {

        driver.findElement(username).sendKeys(user);

        driver.findElement(password).sendKeys(pass);

        driver.findElement(loginButton).click();

    }

}


69. Benefits of Name Locators in POM

  • Locators are centralized.
  • Page classes become easier to maintain.
  • Test methods become cleaner.
  • Form fields are easy to identify.
  • Repeated locator definitions can be avoided.
  • Locator changes can be made in one place.


70. Name Locator with TestNG

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    @Test

    public void loginTest() {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.name("username")).sendKeys("admin");

        driver.findElement(By.name("password")).sendKeys("admin123");

        driver.findElement(By.name("login")).click();

 

        driver.quit();

    }

}


71. Name Locator with TestNG Assertion

import org.testng.Assert;

 

WebElement message = driver.findElement(By.name("successMessage"));

 

Assert.assertTrue(message.isDisplayed());


72. Name Locator with Text Validation

String actualMessage =

    driver.findElement(By.name("successMessage")).getText();

 

Assert.assertEquals(actualMessage, "Registration successful");


73. Name Locator with Reusable Utility

public void enterText(By locator, String text) {

    WebElement element = driver.findElement(locator);

    element.clear();

    element.sendKeys(text);

}

Usage:

enterText(By.name("username"), "admin");

enterText(By.name("email"), "[email protected]");


74. Reusable Click Utility

public void click(By locator) {

    driver.findElement(locator).click();

}

Usage:

click(By.name("login"));

click(By.name("submit"));


75. Explicit Wait Utility for Name Locator

public WebElement waitForElement(By locator) {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    return wait.until(

        ExpectedConditions.visibilityOfElementLocated(locator)

    );

}

Usage:

WebElement username = waitForElement(By.name("username"));

username.sendKeys("admin");


76. Common Exceptions with Name Locator

ExceptionPossible Cause
NoSuchElementExceptionIncorrect name or element not available
ElementNotInteractableExceptionElement exists but cannot be interacted with
ElementClickInterceptedExceptionAnother element blocks the interaction
StaleElementReferenceExceptionDOM changed after locating the element
TimeoutExceptionWait condition was not satisfied


77. NoSuchElementException with Name

Example:

driver.findElement(By.name("wrongName")).click();

If no element contains name="wrongName" in the current browsing context, Selenium can throw NoSuchElementException.

Check:

  • The spelling of the name.
  • Uppercase and lowercase characters.
  • The current page.
  • Whether the element has loaded.
  • Whether the element is inside an iframe.
  • Whether the name is dynamically generated.


78. ElementNotInteractableException

An element may exist in the DOM but not be ready for interaction.

driver.findElement(By.name("username")).sendKeys("admin");

If the field is hidden, disabled, or otherwise not interactable, synchronization or another interaction strategy may be required.


79. ElementClickInterceptedException

This exception can occur when another element overlays the target.

driver.findElement(By.name("submit")).click();

Possible causes include:

  • Popup overlay.
  • Modal dialog.
  • Loading layer.
  • Sticky header.
  • Animation.

An appropriate explicit wait and correct application state should generally be used before attempting the interaction.


80. StaleElementReferenceException

A WebElement reference can become stale if the page or DOM is refreshed or rebuilt.

WebElement username = driver.findElement(By.name("username"));

 

driver.navigate().refresh();

 

username.sendKeys("admin");

After the refresh, the old reference may no longer represent the current DOM element. Locate the element again when necessary.


81. Name Locator Best Practices

  • Use a stable name attribute whenever available.
  • Verify the name value in browser developer tools.
  • Do not assume the name value is unique.
  • Use findElements() for groups that intentionally share the same name.
  • Combine name with value or another stable attribute when necessary.
  • Use explicit waits for dynamically loaded elements.
  • Store important locators in Page Object classes.
  • Avoid hard-coding frequently changing dynamic names.
  • Keep locator names readable.
  • Validate the result after performing an action.


82. Common Mistakes with Name Locator

Mistake 1: Using the Wrong Attribute

Do not confuse name with id.

<input id="username" name="user">

The correct Name Locator is:

By.name("user")

The correct ID Locator is:

By.id("username")

Mistake 2: Assuming Name Is Unique

Multiple elements can have the same name, especially radio buttons and checkboxes.

Mistake 3: Ignoring Dynamic Names

A generated name can change between executions.

Mistake 4: Ignoring Iframes

Elements inside an iframe require switching to the correct frame.

Mistake 5: Not Waiting for Dynamic Content

AJAX and JavaScript-based applications may add the element after the initial page load.


83. Name Locator for Dynamic Forms

Dynamic forms can add fields based on user selections.

driver.findElement(By.name("accountType")).click();

 

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement companyName = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("companyName")

    )

);

 

companyName.sendKeys("ABC Technologies");


84. Name Locator for Payment Options

<input type="radio" name="payment" value="card">

<input type="radio" name="payment" value="upi">

<input type="radio" name="payment" value="netbanking">

Selenium:

List<WebElement> paymentOptions =

    driver.findElements(By.name("payment"));

 

for (WebElement option : paymentOptions) {

    if ("upi".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}


85. Name Locator for Delivery Options

<input type="radio" name="delivery" value="standard">

<input type="radio" name="delivery" value="express">

Selenium:

List<WebElement> deliveryOptions =

    driver.findElements(By.name("delivery"));

 

for (WebElement option : deliveryOptions) {

    if ("express".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}


86. Name Locator for Subscription Options

<input type="radio" name="subscription" value="free">

<input type="radio" name="subscription" value="premium">

List<WebElement> plans =

    driver.findElements(By.name("subscription"));

 

for (WebElement plan : plans) {

    if ("premium".equals(plan.getAttribute("value"))) {

        plan.click();

        break;

    }

}


87. Name Locator for Yes/No Options

<input type="radio" name="newsletter" value="yes">

<input type="radio" name="newsletter" value="no">

List<WebElement> options =

    driver.findElements(By.name("newsletter"));

 

for (WebElement option : options) {

    if ("yes".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}


88. Name Locator with Label and Input

Sometimes the label and input use different attributes.

<label for="username">Username</label>

<input id="username" name="username">

The input can be located directly using:

driver.findElement(By.name("username")).sendKeys("admin");


89. Name Locator in Tables

Name attributes may occasionally be used for action controls inside tables.

<button name="editUser">Edit</button>

<button name="deleteUser">Delete</button>

Selenium:

driver.findElement(By.name("editUser")).click();

If the same name is used in multiple rows, use findElements() or combine the locator with row-specific information.


90. Name Locator for Multiple Products

<button name="addToCart" value="laptop">Add</button>

<button name="addToCart" value="phone">Add</button>

<button name="addToCart" value="tablet">Add</button>

To select the phone:

List<WebElement> buttons =

    driver.findElements(By.name("addToCart"));

 

for (WebElement button : buttons) {

    if ("phone".equals(button.getAttribute("value"))) {

        button.click();

        break;

    }

}


91. Name Locator in Real-World E-Commerce

In an e-commerce application, Name Locators can be used for search fields, checkout forms, address fields, payment options, and form controls when the application provides stable name attributes.

driver.findElement(By.name("search")).sendKeys("Laptop");

driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("address")).sendKeys("Mumbai");

driver.findElement(By.name("checkout")).click();


92. Name Locator in Real-World Registration

driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");

 

WebElement terms = driver.findElement(By.name("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

driver.findElement(By.name("register")).click();


93. Name Locator in Real-World Login

driver.get("https://example.com/login");

 

driver.findElement(By.name("username")).sendKeys("admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.name("login")).click();


94. Name Locator in Test Automation Framework

A framework can organize Name Locators in separate page classes.

public class RegistrationPage {

 

    private WebDriver driver;

 

    private By firstName = By.name("firstName");

    private By lastName = By.name("lastName");

    private By email = By.name("email");

    private By password = By.name("password");

    private By register = By.name("register");

 

    public RegistrationPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void registerUser(

        String first,

        String last,

        String emailValue,

        String passwordValue

    ) {

        driver.findElement(firstName).sendKeys(first);

        driver.findElement(lastName).sendKeys(last);

        driver.findElement(email).sendKeys(emailValue);

        driver.findElement(password).sendKeys(passwordValue);

        driver.findElement(register).click();

    }

}


95. Name Locator and Maintainability

Stable Name Locators can make automation code easier to maintain, particularly when the name attributes are meaningful and remain consistent across application releases.

For example:

By.name("username")

is straightforward to understand and can clearly communicate which field the test is accessing.


96. Name Locator and Readability

Readable automation code helps testers understand the purpose of a test quickly.

driver.findElement(By.name("email")).sendKeys("[email protected]");

The statement clearly indicates that an email field is being populated.


97. Name Locator and Test Stability

Test stability depends on the consistency of the application's HTML. A stable name attribute can provide a useful locator, while a frequently changing name can cause failures.

Before selecting a Name Locator, inspect whether the value is stable across page loads and application releases.


98. Name Locator Decision Flow

Start

  |

  v

Inspect Web Element

  |

  v

Does it have a name attribute?

  |

  +---- No ----> Consider ID / Class / CSS / XPath

  |

 Yes

  |

  v

Is the name stable?

  |

  +---- No ----> Find another stable locator

  |

 Yes

  |

  v

Is the name unique?

  |

  +---- Yes ----> Use By.name("value")

  |

  +---- No ----> Use findElements()

                    |

                    v

             Identify specific

             element by value

             or another attribute


99. Name Locator Validation Checklist

  • Inspect the HTML element.
  • Find the name attribute.
  • Copy the exact name value.
  • Check spelling and case.
  • Determine whether the name is unique.
  • Check whether the name is stable.
  • Use By.name() when appropriate.
  • Use findElements() for grouped controls.
  • Use value or another stable attribute to distinguish multiple elements.
  • Add explicit waits when elements load dynamically.
  • Switch into the correct iframe when required.
  • Validate the expected result after the interaction.


100. Name Locator Quick Reference

ActionExample
Locatedriver.findElement(By.name("username"))
Typedriver.findElement(By.name("username")).sendKeys("admin")
Cleardriver.findElement(By.name("username")).clear()
Clickdriver.findElement(By.name("login")).click()
Get Textdriver.findElement(By.name("message")).getText()
Get Attributedriver.findElement(By.name("email")).getAttribute("value")
Displayeddriver.findElement(By.name("message")).isDisplayed()
Enableddriver.findElement(By.name("submit")).isEnabled()
Selecteddriver.findElement(By.name("terms")).isSelected()
Multiple Elementsdriver.findElements(By.name("payment"))


101. Name Locator Best-Practice Summary

PracticeRecommendation
Stable NamePrefer a name value that remains consistent.
Unique NameUse findElement() when one matching element is expected.
Shared NameUse findElements() for groups such as radio buttons.
Dynamic NameConsider another stable locator strategy.
Specific ElementUse another attribute such as value when multiple elements share the name.
SynchronizationUse explicit waits for dynamically loaded elements.
POMKeep important locators inside Page Object classes.
ValidationVerify the expected result after performing actions.


102. Interview Question: What is a Name Locator?

Answer: A Name Locator is a Selenium WebDriver locator strategy that identifies a web element using the value of its HTML name attribute. In Java Selenium, it is written using By.name("value").


103. Interview Question: What is the Syntax of Name Locator?

Answer:

driver.findElement(By.name("username"));

For entering data:

driver.findElement(By.name("username")).sendKeys("admin");


104. Interview Question: Where is Name Locator Commonly Used?

Answer: Name Locators are commonly used for form fields such as username, password, email, search boxes, textareas, checkboxes, radio buttons, and other controls that contain a suitable name attribute.


105. Interview Question: Is Name Attribute Always Unique?

Answer: No. Multiple elements can share the same name value. Radio buttons often share a name to represent one group, and checkboxes may also use the same name for related options.


106. Interview Question: What If Multiple Elements Have the Same Name?

Answer: Use findElements(By.name("value")) to retrieve all matching elements, then inspect another attribute such as value to identify the required element.


107. Interview Question: Name Locator vs ID Locator?

Answer: ID Locator uses the HTML id attribute, while Name Locator uses the name attribute. IDs are intended to uniquely identify elements, whereas name values can be shared by multiple controls.


108. Interview Question: Name Locator vs XPath?

Answer: Name Locator provides a simple direct way to locate an element using its name attribute. XPath can handle more complex conditions, text matching, and relationships between elements.


109. Interview Question: Can Name Locator Be Used for Radio Buttons?

Answer: Yes. Radio buttons commonly share the same name. In such cases, use findElements() and identify the desired option using another attribute such as value.


110. Interview Question: Can Name Locator Be Used for Checkboxes?

Answer: Yes. If checkboxes have a common name, they can be located using findElements(By.name()) and individual options can be identified using attributes such as value.


111. Interview Question: What Happens If the Name Is Incorrect?

Answer: If no matching element exists in the current browsing context, findElement() can throw NoSuchElementException.


112. Interview Question: How Do You Handle Dynamic Name Values?

Answer: Inspect the HTML for a more stable attribute or relationship. Depending on the application, ID, CSS Selector, XPath, or another reliable locator may be appropriate.


113. Interview Question: Can Name Locator Be Used with Explicit Wait?

Answer: Yes. Any Selenium locator can be passed to explicit wait conditions.

WebElement username = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("username")

    )

);


114. Practical Project: Login Automation Using Name Locator

Automate a login page using Name Locators for username, password, and login button.

driver.get("https://example.com/login");

 

driver.findElement(By.name("username")).sendKeys("admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.name("login")).click();

 

WebElement message = driver.findElement(By.name("successMessage"));

 

System.out.println(message.getText());


115. Practical Project: Registration Automation Using Name Locator

driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");

driver.findElement(By.name("confirmPassword")).sendKeys("Pass@123");

 

WebElement terms = driver.findElement(By.name("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

driver.findElement(By.name("register")).click();


116. Practical Project: Payment Selection

List<WebElement> paymentOptions =

    driver.findElements(By.name("payment"));

 

for (WebElement option : paymentOptions) {

 

    if ("card".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}


117. Practical Project: Multiple Checkbox Selection

List<WebElement> skills =

    driver.findElements(By.name("skills"));

 

for (WebElement skill : skills) {

 

    String value = skill.getAttribute("value");

 

    if ("java".equals(value) || "selenium".equals(value)) {

 

        if (!skill.isSelected()) {

            skill.click();

        }

    }

}


118. Complete Name Locator Example

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class CompleteNameLocatorExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com/login");

 

            WebDriverWait wait =

                new WebDriverWait(driver, Duration.ofSeconds(10));

 

            WebElement username = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.name("username")

                )

            );

 

            WebElement password =

                driver.findElement(By.name("password"));

 

            WebElement loginButton =

                driver.findElement(By.name("login"));

 

            username.sendKeys("admin");

            password.sendKeys("admin123");

            loginButton.click();

 

            WebElement message = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.name("successMessage")

                )

            );

 

            System.out.println(message.getText());

 

        } finally {

            driver.quit();

        }

    }

}


119. Name Locator Automation Workflow

Open Web Page

      |

      v

Inspect HTML

      |

      v

Find name Attribute

      |

      v

Check Name Stability

      |

      v

Is Name Unique?

      |

      +---- Yes ----> Use By.name()

      |

      +---- No -----> Use findElements()

                          |

                          v

                    Check value or

                    another attribute

                          |

                          v

                    Locate Target

                          |

                          v

                    Perform Action

                          |

                          v

                    Validate Result


120. Name Locator Final Checklist

  • Understand the HTML structure.
  • Identify the target element.
  • Find the name attribute.
  • Copy the exact name value.
  • Check whether the name is stable.
  • Check whether multiple elements share the same name.
  • Use By.name() when appropriate.
  • Use findElements() for groups.
  • Use another attribute such as value to distinguish elements when necessary.
  • Use explicit waits for dynamic elements.
  • Handle iframes before locating inner elements.
  • Use Page Object Model for larger projects.
  • Validate the expected result.


121. Conclusion

The Name Locator is an important Selenium WebDriver locator strategy used to identify elements through their HTML name attribute. Its basic Java syntax is By.name("value").

Name Locators are particularly useful when working with forms, input fields, search boxes, textareas, buttons, radio buttons, checkboxes, and other controls that provide stable name attributes.

One important difference between Name and ID locators is that multiple elements can share the same name value. This is common with radio-button groups and checkbox groups. In such situations, findElements() can be used to retrieve the matching elements, after which attributes such as value can be checked to identify the required option.

For reliable Selenium automation, always inspect the HTML, verify the stability of the name attribute, use appropriate synchronization for dynamic content, and keep reusable locators organized through practices such as Page Object Model.

To learn more about Selenium WebDriver, locators, WebElements, TestNG, automation frameworks, and practical testing projects, visit the JustAcademy's Selenium Training Course.

To explore or register for a course demo, visit Register for Course Demo.

whatsapp