"Invalid Selector Used for Locator " error for xpath locator while using findelements

xpath of Job.JobTitles.Add.JobTitleValidMessage is:

//input[@id='jobTitle_jobTitle']/following-sibling::span

It gives NullPointerException on 1st line of code. How to solve this?

List<WebElement> job_valid_message = TestBase.findElements("Job.JobTitles.Add.JobTitleValidMessage");
        if (job_valid_message.size()==1) {
            return !job_valid_message.get(0).isDisplayed();
        } else
            return true;

HTML source of element

<li> <label for="jobTitle_jobTitle">Job Title <em>*</em></label> <input type="text" name="jobTitle[jobTitle]" maxlength="100" id="jobTitle_jobTitle" class="validation-error"><span for="jobTitle_jobTitle" generated="true" class="validation-error">Required</span> </li> 

The correct code should be.

List<WebElement> job_valid_message = TestBase.findElements(By.xpath("//input[@id='jobTitle_jobTitle']/following-sibling::span");
if (job_valid_message.size()>0) {
        return true; //message is displayed
    } else
        return false; //message not displayed

Alternately you can use css span[for='jobTitle_jobTitle' ][class='validation-error'] if you want to access the span directly.

With the assumption that TestBase is a driver controlling some browser, I would use

List<WebElement> job_valid_message = TestBase.findElements(By.cssSelector('span.validation-error');

the class TestBase seems to be your framework class from where you are calling findElements method. Since there is not By definition in the parameter, i can suggest you to check if the parameter is string or By. If it is overloaded with string, what is the default locator definition (like cssSelector, xpath, etc).

Comments
  • Welcome to SO. Can you please share the HTML of Input element.
  • <li> <label for="jobTitle_jobTitle">Job Title <em>*</em></label> <input type="text" name="jobTitle[jobTitle]" maxlength="100" id="jobTitle_jobTitle" class="validation-error"><span for="jobTitle_jobTitle" generated="true" class="validation-error">Required</span> </li>
  • Please share HTML source in question section not in comment section...
  • What is TestBase? How and where is it defined?
  • do you think that this xpath is correct user already shared the html source please edit and correct it..
  • Yes, it is correct xpath. Got the html after my post but still the xpath is good, just confirmed it.
  • what is /following-sibling::span ?
  • the span element which is next to input under the same parent node.
  • @Shivam Poojara If you feel the issue is resolved, please accept the answer by clicking on the check mark below the downvote button on the left hand side in my answer, so that we can close this issue.