JS选择类的第n个成员?

时间:2018-07-06 03:32:34

标签: javascript html

我的页面上有几个<div>,如下所示:

        <div class="countSections"></div>
        <div class="countSections"></div>
        <div class="countSections"></div>
        <div class="countSections"></div>
        <div class="countSections"></div>
        <div class="countSections"></div>

我还有一个JS变量:

var score = 0;

我想使用JavaScript(不是JQuery)选择类 countSections 的第n个成员来进行一些CSS样式设置。

第n 个值将是变量score的值。因此,如果score = 10,那么我想选择 countSections

类的第十个成员

3 个答案:

答案 0 :(得分:1)

.getElementsByClassName() 返回元素的 NodeList 集合,因此您只需传递score作为索引即可。请记住,您还要减去1,请记住数组从0开始:

let score = 3;
const element = document.getElementsByClassName('countSections')[score - 1];
console.log(element.innerHTML);
<div class="countSections">1</div>
<div class="countSections">2</div>
<div class="countSections">3</div>
<div class="countSections">4</div>
<div class="countSections">5</div>
<div class="countSections">6</div>

答案 1 :(得分:0)

使用CSS选择器:

const score = 3;
const selection = document.querySelector(`.countSections:nth-child(${score})`);
<div class="countSections">1</div>
<div class="countSections">2</div>
<div class="countSections">3</div>
<div class="countSections">4</div>
<div class="countSections">5</div>
<div class="countSections">6</div>

答案 2 :(得分:-1)

恕我直言,您可以使用':nth-​​child'选择器。来自CSS-Trick

  

:nth-​​child选择器允许您根据公式根据源顺序选择一个或多个元素。

这里是一个例子:

let score = 3;
const element = document.querySelector('.countSections:nth-child('+score+')')
console.log(element.innerHTML);
<div class="countSections">1</div>
<div class="countSections">2</div>
<div class="countSections">3</div>
<div class="countSections">4</div>
<div class="countSections">5</div>
<div class="countSections">6</div>