Rewrite and refactor getVisibleElements() to make it more generic