2

I'm working on coverting a JQuery project to pure JavaScript and I'm stuck with the following bit of code.

$(".element-has-class:visible")

I thought perhaps something along these lines might work to catch all visible element (in the case of my project list items) but I've had no luck:

function functionName (){
  var elementsOnShow = document.getElementsByClassName('element-has-class').find(isVisible);
}

function isVisible(element) {
  return element.style.display === 'block';
}

(block has been set in the CSS). Is there anyway to get all visible elements within one variable?

Nihar Sarkar
  • 1,187
  • 1
  • 13
  • 26
dedaumiersmith
  • 337
  • 4
  • 14
  • And you're not getting any errors, for instance "`NodeList.find` is not a funtion" or something similar – adeneo Aug 14 '16 at 18:21
  • 1
    Check [THIS](http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom) – Abhi Aug 14 '16 at 18:24

1 Answers1

6

You can convert your nodeList to an Array (read more about it here), which will allow you to use Array.prototype.filter() to get the visible elements:

function functionName (){
  var myNodeList = document.getElementsByClassName('element-has-class'),
      myArray = [].slice.call(myNodeList),
      elementsOnShow = myArray.filter(isVisible);
}

function isVisible(element) {
  return element.offsetWidth > 0
      || element.offsetHeight > 0
      || element.getClientRects().length > 0;
}

The isVisible function you see above is extracted from jQuery 2.2.4's source code (version 3.X.X is not compatible with IE 8 and below).

blex
  • 24,941
  • 5
  • 39
  • 72
  • I would like to add that if the style has been set through classes, use `getComputedStyle().display` to also factor those in. – Matthijs Aug 14 '16 at 18:25
  • 1
    According to https://api.jquery.com/visible-selector/ - 'Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.' So I don't think checking display block will provide the exact behavior as :visible – Jithu Rajan Aug 14 '16 at 18:38
  • @JithuPRajan Alright, I found it in jQuery's source code. See changes – blex Aug 14 '16 at 18:41
  • Thanks so much @blex. For my purposes I think the original code you provided will do the trick but it's really helpful to me (as someone working on their first JavaScript app) to see both versions. – dedaumiersmith Aug 14 '16 at 19:20
  • @dedaumiersmith I'm glad I could help. Good luck with your project – blex Aug 14 '16 at 19:22
  • This saved me, after an hour of searching, thank you! – todbott Jun 17 '20 at 07:29