Home > Net >  Excluding certain elements from Array.prototype.indexOf.call
Excluding certain elements from Array.prototype.indexOf.call

Time:10-23

var el = clickedElement;
var chl = el.closest('li');
var prt = chl.parentNode;
var idx = Array.prototype.indexOf.call(prt.children, chl);

Im using this code to get the index number of clickedElement from the parentNode.. it works most of time.. i want to be able to filter out some elements from the index number

For example..

li.zero
li.first
h2
li.second

If I try this code to get li.second element as index 2 it gives me index '3' because of that h3 tag inbetween.. How can i exclude certain elements from counting?

CodePudding user response:

You could use the Array.prototype.filter method.

It might look something like this:

var idx = Array.prototype.indexOf.call(
  Array.from(prt.children)
    .filter(domNode => domNode.tagName.toLowerCase() === "li"), 
  chl
);

Now you will only check the index for list item elements.

  • Related