如何找到具有动态ID的元素?

发布于 2025-01-29 13:35:43 字数 370 浏览 3 评论 0原文

我想找到此元素:

<tr class=" category-2 saleproductname  " id="21" xpath="1">
<input class="check-box" id="BillInfo_4__isSelected" type="checkbox" value="true" xpath="1">

我正在尝试找到ID,但是ID是动态的,此特定项目可以具有ID =“ Billinfo_0__isselected,有时ID =” Billinfo_1__isseleded,我必须继续更改代码。有什么解决方案吗?这里只有ID = 21是唯一的,但也无法使用。我试图使用ID,因为该类很常见,并且也找到了其他元素。

I want to locate this element:

<tr class=" category-2 saleproductname  " id="21" xpath="1">
<input class="check-box" id="BillInfo_4__isSelected" type="checkbox" value="true" xpath="1">

I am trying to locate the id, but the id is dynamic, this particular item can have id="BillInfo_0__isSelected, sometimes id="BillInfo_1__isSelected and I have to keep on changing them on code. Is there any solution to this? Here only the id = 21 is unique but unable to use this as well. I am trying to use id since the class is common and locates other elements too.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

美男兮 2025-02-05 13:35:43

由于id =“ 21”是唯一的,因此请查询并使用.find()(在父母中会找到)访问输入

cy.get('tr#21')
  .find('input')

,以防万一 如果id =“ 21”每个构建更改,则同一行

cy.get('tr#21')
  .children()
  .eq(0)          // first child element

是一个好主意

<input class="check-box" id="BillInfo_4__isSelected" data-cy="my-input" ... />
cy.get('[data-cy="my-input"]')

Since id="21" is unique, query for that and use .find() (which will find within the parent) to access the input

cy.get('tr#21')
  .find('input')

In case there's several inputs in the same row

cy.get('tr#21')
  .children()
  .eq(0)          // first child element

If id="21" changes per build, it would be a good idea to add a data-cy attribute

<input class="check-box" id="BillInfo_4__isSelected" data-cy="my-input" ... />
cy.get('[data-cy="my-input"]')
凉薄对峙 2025-02-05 13:35:43

您可以使用属性属性selectortor

  1. Billinfo _ 开始。 [class^=“”]
  2. __ ISSELECTED 结束。 [类$ =“”]
const element = document.querySelector('[id^="BillInfo_"][id$="__isSelected"]');

console.log(element);
<div id="BillInfo_4__isSelected"></div>

You can use the attribute selectors to find an element that:

  1. Starts with BillInfo_. [class^=""]
  2. Ends with __isSelected. [class$=""]

const element = document.querySelector('[id^="BillInfo_"][id$="__isSelected"]');

console.log(element);
<div id="BillInfo_4__isSelected"></div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文