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
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With