I don't get this last paragraph, and I don't see why you need it, and least not for the onscreen case, where if any descendant of an element is onscreen then the element itself must be treated as onscreen as well.

Isn't it possible to do a bounded depth-first enumeration of elements in forward or backward document order?