You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Protractor:如何通过同父级子元素定位目标input元素?

Solution to Target Specific Input with Shared ng-model

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:57:31