Sai Sai - 3 months ago 38
jQuery Question

How to return the index of a nodelist using vanilla js?

I have something that I would like to convert from jquery to js.

I am using js to create 12 li elements which when clicked gets the index number, in jquery I used the .index() function to achieve this,

var month = $(".calenderApp__calender__allMonths__month"),
startMonth;

$(month).on('click', function () {
startMonth = $(this).index() + 1;
});


How would I do this is vanilla js, I have gotten as far as

var month = document.querySelectorAll(".calenderApp__calender__allMonths__month"),
startMonth;

for (var i=0; i<month.length; i++) {
month[i].addEventListener("click", function () {
startMonth = this; //returns full html element, just need index number
});
}

Answer

Just store the index in the element.

var month = document.querySelectorAll(".calenderApp__calender__allMonths__month"),
    startMonth;

for (var i=0; i<month.length; i++) {
    month[i].index = i;
	
    month[i].addEventListener("click", function () {
        alert(this.index+1);
    });
}
<ul>
  <li class="calenderApp__calender__allMonths__month">Jan</li>
  <li class="calenderApp__calender__allMonths__month">Feb</li>
  <li class="calenderApp__calender__allMonths__month">March</li>
  <li class="calenderApp__calender__allMonths__month">Apr</li>
</ul>