Dear @Seppo
you can do it way simpler. Unfortunately even that would take too much time to explain for me. But I will try to give you some rough ideas:
You can use this jQuery(this) to avoid the loop. So it grabs the caption text from the inside of the box.
I hope that leads you to the right path.
Best!
Marius