Remove code duplication in DOM traversal routines