I have a few buttons on a page who all share the .btn
class, and only one at any particular time has another class, .selected
, which changes.
In my javascript I've declared an array of elements with the .btn
class:
var btn = document.querySelectorAll(".btn");
I'd like to get the index of the first (and in this case, only) occurrence of the element that also has the .selected
class.
So far as I can tell, without using jQ, I should be able to find the index by using findIndex()
, which requires a testing function. I can't seem to write that function though, because I am unsure how to test if an element from an array contains a particular class, without having a variable for the individual element.
Finding the index of the element with class in native Javascript -- This question from Nov '16 seems to ask nearly the same question but the top answer suggests using document.getElementByClass()
which returns an array, not an index.
Test if an element contains a class? -- Here the answer appears to work for testing individual elements, but if I'm trying to iterate through an array without a loop (i.e. using something like findIndex()
), I don't have a var
to use the element.contains
notation.
So more or less I'm trying to pass the index into another function:
someFunc(btn.findIndex(element.classList.contains("selected"));
, but struggling to determine how to use the indexOf()
method to find the location.
I'm obviously new to JS, so any and all help is appreciated!