Extract function for looping over elements matching a selector