I have a few <div>
s on my page like so:
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
I also have a JS variable:
var score = 0;
I would like to, using JavaScript (not JQuery), select the nth member of the class countSections to do some CSS styling.
The nth value will be the variable score
's value. So if score = 10
then I would like to select the 10th member of the class countSections
I have a few <div>
s on my page like so:
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
<div class="countSections"></div>
I also have a JS variable:
var score = 0;
I would like to, using JavaScript (not JQuery), select the nth member of the class countSections to do some CSS styling.
The nth value will be the variable score
's value. So if score = 10
then I would like to select the 10th member of the class countSections
- developer.mozilla/en-US/docs/Web/API/Document/… – hisener Commented Jul 6, 2018 at 3:36
3 Answers
Reset to default 2.getElementsByClassName()
returns a NodeList collection of elements, so you can just pass the score
as your index. Keep in mind that you'll also want to subtract 1, remembering that arrays start at 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>
Use css selectors:
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>
IMHO you can use ':nth-child' selector. From CSS-Trick:
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula.
Here is an example:
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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745103619a4611426.html
评论列表(0条)