TransWikia.com

Get non hidden element with previousElementSibling

Stack Overflow Asked by Jens Törnell on November 7, 2021

I have a long list of items. One of them is active. From that active item I want to go to the previous one. I can do that with previousElementSibling.

The problem is that I want to skip the hidden elements. How can I do that?

const active = document.querySelector('.active');
const prev = active.previousElementSibling;
console.log(active);
console.log(prev);
<div></div>
<div hidden></div>
<div class="active"></div>

In the real world, the list is dynamic and longer so no crazy hacks will work.

2 Answers

You can do this by looping to repeatedly walk through previousElementSibling's, until you find one that's not hidden. For example:

const active = document.querySelector('.active');

// Get the previous sibling
let result = active.previousElementSibling;

// If it's hidden, continue back further, until a sibling isn't hidden
while (result && result.hidden == true) {
   result = result.previousElementSibling;
}

if (result) {
  // You got a non-hidden sibling!
  console.log(result);
} else {
  // There is no previous sibling that's not hidden
}

Answered by Tim Perry on November 7, 2021

You can keep going to previous elements until you find one that is not hidden or until you reach the first element :

const active = document.querySelector('.active');
let prev = active.previousElementSibling;
while (prev !== null) {
  if (!prev.hidden) break;
  prev = prev.previousElementSibling;
}
console.log(active);
console.log(prev);

Answered by Ki Jéy on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP