Refactor refactorElement() function to make it more flexible