简体   繁体   中英

Using css selector, how to grab nth child of of element using it's class

After getting the number of elements with a specific class, how do I iterate through them?

I am using webdriver to automate some tests. I can grab the number of elements with a specific class using

<div>
    <tr class="test"></tr>
    <tr class="test"></tr>
    <tr class="test"></tr>
    <tr class="test"></tr>
</div>
let trNum = (await client.elements("div > tr.test")).value.length;

trNum will equal 4 in this case. I want to iterate through each of the elements, preferably using nth-child. How can I do this? I've tried

"div > tr.test:nth-child(1)"

but it didn't work

Use querySelectorAll to select the unknown amount of .test classes. After that, loop throught this list with querySelector because you know for sure the item exists.

<div>
  <div class="test">item 1</div>
  <div class="test">item 2</div>
  <div class="test">item 3</div>
  <div class="test">item 4</div>
</div>

<script>
// nodelist (in example node 0 - 3)
let divs = document.querySelectorAll(".test");
// How many nodes (in example 4)
let divCount = divs.length;
// loop through nth-child(1) - nth-child(4) <=== not 0 - 3
var i, selector, divItem;
for (i = 1; i <= divCount; i++) {
  selector = ".test:nth-child(" + i + ")";
  divItem = document.querySelector(selector);
  console.log(divItem.innerHTML);
}
</script>

For explanation I did not put lines together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM