Selecting elements from DOM

你。 提交于 2019-12-10 18:46:43

问题


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]

or using a DOM tree

. 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?

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

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

回答1:


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');
  • .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



回答2:


You can just give each span a unique class.

<span class="card-1">CONTENT</span> 


来源:https://stackoverflow.com/questions/54910527/selecting-elements-from-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!