Search code examples
selenium-webdrivercss-selectorsprotractorchaining

Chaining an element using css containing text and accessing an associated field


I need to access the input field in the below html. The way the page is setup I need to chain using the 'Address Line 1' text and then sending text to the input field. The input field id changes and so doesn't the layout of the fields depending on user preference. I am struggling. If you need some more information feel free to ask I did not want to overload with too much information.

<td class="labelCol requiredInput">
  <label for="00N36000000xina"><span class="assistiveText">*</span>Address Line 1</label>
</td>
<td class="dataCol col02">
  <div class="requiredInput">
    <div class="requiredBlock"></div>
    <input id="00N36000000xina" maxlength="255" name="00N36000000xina" size="20" tabindex="4" type="text">
  </div>
</td>

I have accessed like this:

element(by.css('div.pbSubsection:nth-child(3) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > input'))

However depending on where the user puts the fields it can move around. So what I was hoping was to be able to access the label\ and use that to pinpoint its input field.


Solution

  • I don't know protractor but I cobbled together some code that hopefully will work or be close and I'll give you the thought process and some info and hopefully you can use it to fix my code, if needed, and solve the problem.

    Start by finding an element by XPath, "//label[text()='Address Line 1']". This searches for a LABEL tag that contains "Address Line 1". Once you find that element, get the label attribute. From your HTML, this label is the id for the INPUT element you want. Now use the id to find the element and do with it what you want.

    id = element(by.xpath("//label[text()='Address Line 1']")).getAttribute("label")
    input = element(by.id(id))
    input.sendkeys("some text")