Pick index of Node list that doesnt have certain class

var allArticle = document.querySelectorAll("article");
console.log(allArticle);

The above code renders this in the browser β†’

NodeList(3) [article.commonclass, article.commonclass.holidayclass, article.commonclass.holidayclass]
0: article.commonclass
1: article.commonclass.holidayclass
2: article.commonclass.holidayclass
length: 3

I want to pick the index where there is no holidayclass, but since it is a part of the slides so the situation will be varying:

NodeList(3) [article.commonclass, article.commonclass.holidayclass, article.commonclass.holidayclass]
0: article.commonclass.holidayclass
1: article.commonclass.holidayclass
2: article.commonclass
length: 3
NodeList(3) [article.commonclass, article.commonclass.holidayclass, article.commonclass.holidayclass]
0: article.commonclass.holidayclass
1: article.commonclass
2: article.commonclass.holidayclass
length: 3

I was unable to accomplish this. Please guide me so that I can take it further.

As a nodeList only has forEach as an array-handling method, we can use Array.from() to give us access to some array-based techniques, such as filter.

var allArticle = Array.from(document.querySelectorAll("article"));
var noHoliday = allArticle.filter(function (article) {
    const hasHoliday = article.classList.contains("holidayclass");
    return !hasHoliday;
});
console.log(noHoliday); // [article.commonclass]
1 Like

Hi there, sir wat advantage did we get converting to an array. I wanted the index number β†’

0 or 1 or 2. This is still not giving the index.

Situation: This is a slider, and I need this number in the sliding events.

Total number of slides I have got through this β†’

var allArticle = document.querySelectorAll("article");
var numArticleLength = allArticle.length;
document.querySelector(".totalslide").innerHTML = numArticleLength;

But I need the current slide displayed, for that I was looking for the index number of the one that doesn’t has class holidayclass

The advantage is that we have access to a wider range of array-based methods that can help.

Ahh good, there is another array method that can help, in this case it is findIndex() method.

var allArticle = Array.from(document.querySelectorAll("article"));
var currentIndex = allArticle.findIndex(function (article) {
    return !(article.classList.contains("holidayclass"));
});
console.log(currentIndex); // 1
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.