dedaumiersmith dedaumiersmith - 3 months ago 10
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.

$(".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?

Answer

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).

Comments