Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS select nth member of class?

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 = 10then I would like to select the 10th member of the class countSections

like image 247
Flame Stinger Avatar asked Oct 21 '25 04:10

Flame Stinger


1 Answers

.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>
like image 167
Obsidian Age Avatar answered Oct 22 '25 19:10

Obsidian Age