It can't be set outside of the loop as link changes every iteration so by extension so will link.search and linkQuery.length.