Tomas Kaidl
Tomas Kaidl

Reputation: 231

Is there way to have more nextElementSibling s in line?

I need to point to exactly fourth nextElementSibling, is there any simplified way to do that?

var x = document.activeElement.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling;

Upvotes: 0

Views: 94

Answers (1)

Jannis Ioannou
Jannis Ioannou

Reputation: 2181

Use the .reduce() method on an array of (in your case) 4 elements, to call nextElementSibling multiple times.

var x = Array.from({length:4})
  .reduce((acc)=>acc.nextElementSibling, document.activeElement)

Alternatively, you can create a helper generic method, to be used with any function.


// Calls the given func for numIterations, 
// passing each time the result of previous iteration. 
// The result of last iteration is returned.
let callFor = (func, initialArg, numIterations)=>
  Array.from({length:numIterations})
       .reduce((acc)=>func.call(undefined, acc), initialArg);

Then call it like this.

var x = callFor((el)=>el.nextElementSibling, document.activeElement, 4)

Upvotes: 0

Related Questions