Maybe extract the common code that finds the tab index into a separate function?