dedaumiersmith dedaumiersmith - 6 months ago 27
Javascript Question

Finding only visible elements using JavaScript

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


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 === 'block';

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


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 = [],
      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).