简体   繁体   English

querySelectorAll并选择特定的子代

[英]querySelectorAll and selecting specific children

Assume I have the HTML below 假设我有下面的HTML

HTML 的HTML

<div class="container">
  <p>Test1</p>
  <p>Test5</p>
</div>

<div class="container">
  <p>Test3</p>
  <p>Test7</p>
</div>

I want to select the 2nd child in each .container via vanilla javascript (Test5 and Test 7). 我想通过香草javascript(Test5和Test 7)在每个.container选择第二个孩子。

How would I do that? 我该怎么做?

If I do this 如果我这样做

var container = document.querySelectorAll(".container p");
console.log(container[1]);

It only returns Test5 rather than the second child in both containers 它只返回Test5而不是两个容器中的第二个孩子

Any suggestions? 有什么建议么? Thanks! 谢谢!

Use the :nth-child selector: 使用:nth-child选择器:

 var secondChilds = document.querySelectorAll(".container p:nth-child(2)"); console.log(secondChilds); 
 <div class="container"> <p>Test1</p> <p>Test5</p> </div> <div class="container"> <p>Test3</p> <p>Test7</p> </div> 

Another approach using ES6. 使用ES6的另一种方法。 Maybe a lil' bit overcomplicated - but works fine. 可能有点复杂-但效果很好。

 let elems = document.getElementsByClassName('container'); Array.from(elems).forEach(function(v){ v.children[1].style.color = 'blue'; }) 
 <div class="container"> <p>Test1</p> <p>Test5</p> </div> <div class="container"> <p>Test3</p> <p>Test7</p> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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