Protractor:如何通过同父级子元素定位目标input元素?
First, let's break down the problem: you need to target an <input> that shares an ng-model with others, but it's nested inside the same parent <field class="testClass"> as a <label> with a unique ID. Your original XPath was searching globally, which is why it kept picking the first matching input.
Here are two reliable ways to fix this:
1. Traverse from the Unique Label to the Input
Start by locating the label with its unique ID, then navigate up to the shared parent <field class="testClass">, and finally find the input within that parent scope:
// Locate the target label using its unique ID const targetLabel = element(by.id('21')); // Traverse up to the common parent field, then find the input inside it const targetInput = targetLabel.element(by.xpath('./ancestor::field[contains(@class, "testClass")]//input[@ng-model="vm.ItemInfos[xIndex][yIndex]"]'));
2. Direct XPath to the Input via Its Parent Field
You can also write a single XPath that directly targets the input by first identifying its parent field (which contains the unique label):
const targetInput = element(by.xpath('//field[contains(@class, "testClass") and .//label[@id="21"]]//input[@ng-model="vm.ItemInfos[xIndex][yIndex]"]'));
Why This Works
contains(@class, "testClass")ensures we match the parent field even if it has additional class names (instead of using an exact@class="testClass"match which can fail if other classes are present).- The
.//label[@id="21"]condition locks us to the specific field that contains your target label, so we only search for the input within that limited scope—no more picking the first global match.
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

