从DOM中选择元素 [英] Selecting elements from DOM

查看:122
本文介绍了从DOM中选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在页面内容上,我有多张卡片组织成一个网格

On my page contents, I have multiple cards organized as a grid

 __________________
|  ____    ____    |
| |    |  |    |   |
| |    |  |    |   |
| |____|  |____|   |
|                  |
|  ____    ____    |
| |    |  |    |   |
| |    |  |    |   |
| |____|  |____|   |
|__________________|

我的问题是每个卡片容器都具有相同的类,我想在容器内选择一个不同的元素.示例:

My issue is that each card container has the same class, and I want to select a distinct element inside a container. Example:

<div class="parent-container">
  <div class="container">
    <h2> Distinct title 1 </h2>
  </div>
  <div class="container">
    <div class="another-container">
      <button>
        <span> Click Here! </span>
      </button>
    </div>
  </div>
</div>

[repeat X times]

或使用DOM树

. Parent div
|_ child div
|  |_ <h2> Distinct title 3 </h2>
|
|_ child div
   |_ grandchild div
      |_ button
         |_ <span> Click Here! </span>

因此,假设我想在第三个容器上选择一个元素.选择器查询会如何?

So, supposedly I want to select an element on the third container. How would the selector query be?

基于@lostlemon的答案,我的查询如下:

Based on @lostlemon answer, my query is the following:

await t
  .click(Selector('span')
  .parent(3)
  .child('h2')
  .withExactText('Distinct title 3'));

推荐答案

在这种情况下,如果您总是要选择第三个容器,则可以使用nth-childnth-of-type:

If you always want to select the third container in this scenario, you could use nth-child or nth-of-type:

await t.click('div:nth-child(3) > span');

如果您需要单击基于标题的跨度,请尝试以下操作:

If you need to click on the span based on title, try this:

await t
    .click(Selector('span').parent('.parent-container')
    .child('h2').withExactText('Distinct title 3');

    如果所有<span>具有相同的文本,则可以删除
  • .withText()
  • 如果您要定位容器类,请确保您的父选择器正在尝试查找类而不是元素
  • .find()寻找一个元素,因此它与不同的标题文本不匹配
    • .withText() can be removed if all the <span>s have the same text
    • make sure your parent selector is trying to find the class and not an element if you're targeting the container class
    • .find() looks for an element, so it wouldn't match the distinct title text
    • 这篇关于从DOM中选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆