0

I use vanilla javascript, no jQuery.

In my code I have something that looks like this:

item.closest('ul').closest('li').closest('ul').classList.add('active');

While it works, it does not look that nice. I repeat closest three times.

Is it possible to so something smarter in this case?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

1 Answers1

1

There is no standard way of making this shorter.

You can:

  1. Add a class to the element you are trying to select. That would make your selector look like this : item.closest('ul.myClass').classlist.add('active')
  2. Create a function that wraps the closest chain creation :

    function closestChain(item) {
        return Array.from(arguments).reduce((acc, val) => {
            return acc.closest(val);
        });
    }
    
    closestChain(item, 'ul', 'li', 'ul').classlist.add('active');
    
  3. Or you can wait for the has CSS selector to be available
Ebatsin
  • 552
  • 5
  • 17