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?

2
  • And you're not getting any errors, for instance "NodeList.find is not a funtion" or something similar Commented Aug 14, 2016 at 18:21
  • 1
    Check THIS Commented Aug 14, 2016 at 18:24

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

I would like to add that if the style has been set through classes, use getComputedStyle().display to also factor those in.
According to 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
@JithuPRajan Alright, I found it in jQuery's source code. See changes
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 I'm glad I could help. Good luck with your project
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.